項目中的一個需求選擇數(shù)量不使用選擇器,而是使用數(shù)字鍵盤上面帶確定按鈕,做了一些調(diào)研把這個功能完成了轴术,沒能夠把這個功能封裝起來用很是不足,希望有人看到這篇博客去實現(xiàn)钦无。
創(chuàng)建一個放在數(shù)字鍵盤上的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要根據(jù)手機的尺寸做適配决记。Button的點擊方法是點擊后要做的業(yè)務(wù)邏輯摧冀。
鍵盤監(jiān)聽
-(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的處理了系宫,還有需要優(yōu)化的地方索昂,希望大家一起說說。