可以通过监听键盘的弹出和消失事件,在弹出时将文本框的底部坐标与键盘高度作比较,如果文本框被遮盖,则将整个视图上移相应的距离,以保证文本框不被遮盖。代码示例:
// 添加键盘出现和消失的监听事件
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
- (void)keyboardWillShow:(NSNotification *)notification {
NSDictionary *userInfo = [notification userInfo];
CGFloat keyboardHeight = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
CGFloat duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
CGRect rect = [self.view convertRect:self.textField.frame fromView:self.scrollView];
CGFloat bottom = rect.origin.y + rect.size.height;
CGFloat offset = bottom - (self.view.frame.size.height - keyboardHeight);
if (offset > 0) {
[UIView animateWithDuration:duration animations:^{
CGRect frame = self.scrollView.frame;
frame.origin.y -= offset;
self.scrollView.frame = frame;
}];
}
}
- (void)keyboardWillHide:(NSNotification *)notification {
NSDictionary *userInfo = [notification userInfo];
CGFloat duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
[UIView animateWithDuration:duration animations:^{
CGRect frame = self.scrollView.frame;
frame.origin.y = 0;
self.scrollView.frame = frame;
}];
}