在iOS开发过程中,监听键盘的弹出是十分常用的一项功能,可以有效地提升用户在使用过程中的体验
概括的讲,监听键盘的弹出是很简单的一项功能,本质就是给当前的控制器添加两个观察者
observer
,一个监听键盘弹出,另一个监听键盘收起,然后相应的改变输入框
和当前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];
// 添加观察者,监听键盘弹出
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardDidShow:) name:UIKeyboardWillShowNotification object:nil];
// 添加观察者,监听键盘收起
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardDidHide:) name:UIKeyboardWillHideNotification object:nil];
// 创建一个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];
// 取得键盘的动画时间,这样可以在视图上移的时候更连贯
double duration = [[notifiction.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
NSLog(@"%f",duration);
//调整放置有textView的view的位置
//设置动画
[UIView beginAnimations:nil context:nil];
//定义动画时间
[UIView setAnimationDuration:duration];
[UIView setAnimationDelay:0];
//设置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)];
//提交动画
[UIView commitAnimations];
}
键盘收起的操作
- (void)keyBoardDidHide:(NSNotification*)notification {
//定义动画
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.25];
//设置view的frame,往下平移
[(UIView *)[self.view viewWithTag:1000] setFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 70, [UIScreen mainScreen].bounds.size.width, 70)];
[UIView commitAnimations];
}
供大家参考一下
网友评论