在iOS開發(fā)過程中,監(jiān)聽鍵盤的彈出是十分常用的一項(xiàng)功能昵时,可以有效地提升用戶在使用過程中的體驗(yàn)
概括的講尊搬,監(jiān)聽鍵盤的彈出是很簡單的一項(xiàng)功能,本質(zhì)就是給當(dāng)前的控制器添加兩個(gè)觀察者
observer
,一個(gè)監(jiān)聽鍵盤彈出途样,另一個(gè)監(jiān)聽鍵盤收起江醇,然后相應(yīng)的改變輸入框
和當(dāng)前View
的frame
就可以了
- 下面可以用簡潔的Demo示范一下(只改變輸入框)
- (void)viewDidLoad {
[super viewDidLoad];
// 輸入框
UITextView *tf = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, [UIScreen mainScreen].bounds.size.width - 20, 50)];
tf.delegate = self;
tf.backgroundColor = [UIColor orangeColor];
[tf.layer setCornerRadius:6];
[self.view addSubview:tf];
// 添加觀察者,監(jiān)聽鍵盤彈出
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardDidShow:) name:UIKeyboardWillShowNotification object:nil];
// 添加觀察者何暇,監(jiān)聽鍵盤收起
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardDidHide:) name:UIKeyboardWillHideNotification object:nil];
// 創(chuàng)建一個(gè)textView的容器View
UIView *keyView = [[UIView alloc]initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 70, [UIScreen mainScreen].bounds.size.width, 70)];
keyView.backgroundColor = [UIColor lightGrayColor];
keyView.tag = 1000;
[keyView addSubview:tf];
[self.view addSubview:keyView];
}
- 以上的代碼搭出了簡單的界面陶夜,簡單的示例一下彈出輸入框,
View
的彈出此處就不示例了
鍵盤彈出的操作
- (void)keyBoardDidShow:(NSNotification*)notifiction {
//獲取鍵盤高度
NSValue *keyboardObject = [[notifiction userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey];
NSLog(@"%@",keyboardObject);
CGRect keyboardRect;
[keyboardObject getValue:&keyboardRect];
//得到鍵盤的高度
//CGRect keyboardRect = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];
// 取得鍵盤的動(dòng)畫時(shí)間裆站,這樣可以在視圖上移的時(shí)候更連貫
double duration = [[notifiction.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
NSLog(@"%f",duration);
//調(diào)整放置有textView的view的位置
//設(shè)置動(dòng)畫
[UIView beginAnimations:nil context:nil];
//定義動(dòng)畫時(shí)間
[UIView setAnimationDuration:duration];
[UIView setAnimationDelay:0];
//設(shè)置view的frame条辟,往上平移
[(UIView *)[self.view viewWithTag:1000] setFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height-keyboardRect.size.height-70, [UIScreen mainScreen].bounds.size.width, 70)];
//提交動(dòng)畫
[UIView commitAnimations];
}
鍵盤收起的操作
- (void)keyBoardDidHide:(NSNotification*)notification {
//定義動(dòng)畫
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.25];
//設(shè)置view的frame,往下平移
[(UIView *)[self.view viewWithTag:1000] setFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 70, [UIScreen mainScreen].bounds.size.width, 70)];
[UIView commitAnimations];
}
供大家參考一下