1、监听
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];/**< 键盘将要出现的通知 */
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillDismiss:) name:UIKeyboardWillHideNotification object:nil];/**< 键盘将要消失的通知 */
2、touchesBegan:让键盘在点击视图的时候收起来
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
//键盘消失
[self.password resignFirstResponder];/**< 让某一个textFlies或者textView 键盘消失 */
//从输入源的父视图消失
[self.view endEditing:YES];/**< 让父视图上面的原件的键盘消失 */
}
2、键盘的移动
#pragma mark -- 键盘监听
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[_bgview removeFromSuperview];
[self.view endEditing:YES];/**< 让父视图上面的原件的键盘消失 */
}
- (void)keyBoardWillShow:(NSNotification *)notification {
_bgview = [[UIView alloc]initWithFrame:self.view.frame];
[self.view addSubview:_bgview];
//获取第一相应者
UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
UIView *firstResponder = [keyWindow performSelector:@selector(firstResponder)];
UIView *view = [firstResponder superview];
//获取键盘的frame
CGRect keyboardRect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
if (keyboardRect.origin.y < CGRectGetMaxY(view.frame)) {
//获取键盘出现的时间
NSTimeInterval interal = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//计算 视图应该移动的位置
CGFloat offset = CGRectGetMaxY(view.frame) - keyboardRect.origin.y ;
[UIView animateWithDuration:interal animations:^{
self.view.bounds = CGRectMake(0, offset, kWidth, self.view.frame.size.height);
self.navigView.center =CGPointMake(self.view.center.x, 32 + offset);
}];
}
}
- (void)keyboardWillDismiss:(NSNotification *)notification {
[_bgview removeFromSuperview];
//获取键盘消失的时间
NSTimeInterval interal = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
[UIView animateWithDuration:interal animations:^{
self.view.bounds = CGRectMake(0, 0, kWidth, self.view.frame.size.height);
self.navigView.center =CGPointMake(self.view.center.x, 32 );
}];
}