一、通过接收键盘弹出、回退时发出的通知来进行键盘的相关的处理:
- (void)viewDidLoad {
[super viewDidLoad];
//键盘弹出时接收通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardWillShowNotification object:nil];
//键盘回退时接收通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHide:) name:UIKeyboardWillHideNotification object:nil];
}
//收到键盘弹出通知
-(void)keyboardShow:(NSNotification *)note
{
CGRect keyboardRect = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
self.toolBottomDistance.constant = keyboardRect.size.height;
[UIView animateWithDuration:0.25 animations:^{
[self.view layoutIfNeeded];
}];
}
//收到键盘回退的通知
-(void)keyboardHide:(NSNotification *)note
{
self.toolBottomDistance.constant = 0;
[UIView animateWithDuration:0.25 animations:^{
[self.view layoutIfNeeded];
}];
}
//滑动屏幕时回退键盘
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
[self.view endEditing:YES];
}
//当有键盘弹出、回退时,都会发通知,如果此控制器已销毁,通知会根据原来的地址找此控制器,程序会崩溃
-(void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
其中 toolBottomDistance 为工具条底部和 view 底部之间的约束。
二、通过接收键盘 frame 改变时发出的通知来进行相关的键盘处理:
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardAction:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
-(void)keyboardAction:(NSNotification *)note
{
CGRect rect = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
self.toolBottomDistance.constant = [UIScreen mainScreen].bounds.size.height - rect.origin.y;
[UIView animateWithDuration:duration animations:^{
[self.view layoutIfNeeded];
}];
}
//滑动屏幕时回退键盘
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
[self.view endEditing:YES];
}
//当有键盘弹出、回退时,都会发通知,如果此控制器已销毁,通知会根据原来的地址找此控制器,程序会崩溃
-(void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
以上改约束的方法还可以通过改 transform 来实现:
-(void)keyboardAction:(NSNotification *)note
{
CGRect rect = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
//清空 transform
self.view.transform = CGAffineTransformIdentity;
CGFloat ty = [UIScreen mainScreen].bounds.size.height - rect.origin.y;
[UIView animateWithDuration:duration animations:^{
self.view.transform = CGAffineTransformMakeTranslation(0, -ty);
}];
}
其它:回退键盘的三种方式:
- 方式一:注销第一响应者
[self.messageField resignFirstResponder];
- 方式二:停止编辑模式
[self.messageField endEditing:YES];
- 方式三:view 中所有控件停止编辑模式
[self.view endEditing:YES];
第三种方式使用比较方便,建议使用