避免键盘遮挡

避免键盘遮挡以及隐藏键盘

很多时候在用户输入时弹出键盘都会阻挡到UI的显示,因此我们应该监听键盘弹出的通知以作UI的位置调整。

键盘的通知

  • UIKeyboardWillShowNotification
  • UIKeyboardDidShowNotification
  • UIKeyboardWillHideNotification
  • UIKeyboardDidHideNotification
  • UIKeyboardDidChangeFrameNotification
  • UIKeyboardWillChangeFrameNotification

键盘通知的字典内容分析

1. 监听键盘即将改变Frame的通知

1
2
3
4
5
6
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];

- (void)keyboardWillChangeFrame:(NSNotification *)notification {
NSDictionary *keyboardInfo = notification.userInfo;
NSLog(@"keyboardInfo is %@",keyboardInfo);
}

2. 通知内容分析

1
2
3
4
5
6
7
8
9
10
2016-02-18 14:17:02.843 test[1304:463755] keyboardInfo is {
UIKeyboardAnimationCurveUserInfoKey = 7; // 动画执行的节奏(速度)
UIKeyboardAnimationDurationUserInfoKey = "0.25";// 键盘弹出/隐藏所需的时间
UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 0}}"; // 键盘的边界(Bound)
UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 667}"; // 弹出前的中点
UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 667}"; // 弹出后的中点
UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 0}}"; // 弹出前的 Frame
UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 667}, {375, 0}}"; // 弹出后的 Frame
UIKeyboardIsLocalUserInfoKey = 1;
}

动画调整View的Y值

根据通知接收的字典得到弹出后键盘的Y值以及键盘弹出的时间来调整View的Y值以避免被遮挡。

View调整的Y值 = 键盘弹出后的Y值 - 屏幕高度

1
2
3
4
5
6
7
8
9
10
11
12
13
- (void)keyboardFramWillChange:(NSNotification *)notification {
NSDictionary *keyboardInfo = notification.userInfo;
NSLog(@"keyboardInfo is %@",keyboardInfo);

// 键盘弹出所需要的时间
CGFloat animationTime = [keyboardInfo[UIKeyboardAnimationDurationUserInfoKey]floatValue];
// 键盘弹出后的 Frame
CGRect keyboardFrame = [keyboardInfo[UIKeyboardFrameEndUserInfoKey]CGRectValue];
// 动画调整 View 的 Y值
[UIView animateWithDuration:animationTime animations:^{
self.view.transform = CGAffineTransformMakeTranslation(0, keyboardFrame.origin.y - SCREENHEIGHT);
}];
}

点击空白地方隐藏键盘

1
2
3
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self.textField endEditing:YES];
}

定制 ReturnKey 来隐藏键盘或者跳到下一个 textField

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 1. 遵守 `UITextFieldDelegate` 协议
// 2. 设置 `textField` 的 `delegate` 为当前控制器
// 3. 设置协议的方法:`- (BOOL)textFieldShouldReturn:(UITextField *)textField`

[self.textField1 setDelegate:self];
// Returnkey设置为`next`
[self.textField1 setReturnKeyType:UIReturnKeyNext];
// 根据文本输入框有无字符时自动开启关闭 `Returnkey`
[self.textField1 setEnablesReturnKeyAutomatically:YES];

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[self.textFeild1 resignFirstResponder];
// [self.textFeild1 becomeFirstResponder];
return YES;
}
坚持原创技术分享,您的支持将鼓励我继续创作!