项目中的一个需求选择数量不使用选择器,而是使用数字键盘上面带确定按钮,做了一些调研把这个功能完成了,没能够把这个功能封装起来用很是不足,希望有人看到这篇博客去实现。
创建一个放在数字键盘上的Button
Button在- (void)viewDidLoad方法里就要初始化,这块让我觉的这么做很low,本来想封装一个继承UITextField的类,Button的什么都封装在里,但会有一些bug,每次键盘弹出时,Button总不能做到与键盘同步,所以就这么做了。
// 键盘按钮
CGFloat btnH = 0;
if (kScreenWidth == 320 || kScreenWidth == 375) {
btnH = 160;
}else if (kScreenWidth == 414){
btnH = 169;
}
self.doneInKeyboardButton = [UIButton buttonWithType:UIButtonTypeCustom];
self.doneInKeyboardButton.backgroundColor = kMainUIColor;
[self.doneInKeyboardButton setTitle:@"确定" forState:UIControlStateNormal];
[self.doneInKeyboardButton addTarget:self action:@selector(doneInKeyboardButtonClick:) forControlEvents:UIControlEventTouchUpInside];
self.doneInKeyboardButton .frame = CGRectMake(0, kScreenHeight,kScreenWidth/3-2 , btnH / 3);
变量btnH是Button要根据手机的尺寸做适配。Button的点击方法是点击后要做的业务逻辑。
键盘监听
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:YES];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}
- (void)handleKeyboardWillShow:(NSNotification *)notification{
NSUInteger cnt = [[UIApplication sharedApplication ] windows ].count;
// 获得UIWindow 层
UIWindow * keyboardWindow = [[[UIApplication sharedApplication ] windows ] objectAtIndex:cnt - 1];
[keyboardWindow addSubview:self.doneInKeyboardButton];
NSDictionary *info = [notification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
[UIView animateWithDuration:0.25 animations:^{
self.doneInKeyboardButton.frame= CGRectMake(0, kScreenHeight - self.doneInKeyboardButton.height, self.doneInKeyboardButton.width , self.doneInKeyboardButton.height);
}];
}
- (void)handleKeyboardWillHide:(NSNotification *)notification{
[UIView animateWithDuration:0.25 animations:^{
self.doneInKeyboardButton.frame= CGRectMake(0, kScreenHeight, self.doneInKeyboardButton.width , self.doneInKeyboardButton.height);
}];
}
大体的代码就是这些,其它的就是UITextField的处理了,还有需要优化的地方,希望大家一起说说。