- 在iOS上有两个通知可以监听键盘弹出和收回:
UIKeyboardWillShowNotification(弹出)和UIKeyboardWillHideNotification(收回)。可以分别监听两个通知调整输入框的位置。但也有一个监听起来更为方便的通知UIKeyboardWillChangeFrameNotification(直接监听键盘的frame改变,弹出或收回)代码如下:
//监听键盘弹出或收回通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
- 当键盘frame改变(弹出和收回)时的操作:
- (void)keyboardChange:(NSNotification *)note{
//拿到键盘弹出的frame
CGRect frame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
//修改底部输入框的约束
self.bottomConstrain.constant = [UIScreen mainScreen].bounds.size.height - frame.origin.y;
//键盘弹出所需时长
CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//添加输入框弹出和收回动画
[UIView animateWithDuration:duration animations:^{
//立即刷新进行重新布局
[self.view layoutIfNeeded];
}];
}
- 移除通知
//移除通知
- (void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}