问题
之前做过好几个项目,UITableViewCell
嵌套着UITextField
或者UITextView
,当弹起键盘时会遮挡编辑窗口,之前一直用改变UITableView
的Frame
方式,然后设置UITableView
的ContentOffset
方式滚动到对应的编辑位置,但是这种方式存在着不友好的UI交互。
解决思路
-
监听键盘
UIKeyboardWillShowNotification 和 UIKeyboardWillHideNotification
-
在键盘弹起的时候改变
UITableView的contentInset
-
调用
UITableView
的API- (void)scrollToRowAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animated;
滚动到指定的位置 -
键盘弹下时同样改变
UITableView的contentInset
恢复到原来位置
代码
[[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];
NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = [value CGRectValue];
CGFloat height = keyboardRect.size.height;
NSNumber *durationTime = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
[UIView animateWithDuration:durationTime.floatValue + 0.1 animations:^{
} completion:^(BOOL finished) {
self.tableView.contentInset = UIEdgeInsetsMake(0, 0, height, 0);
/**滚动到指定的cell*/
[self.tableView scrollToRowAtIndexPath:self.selectIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}];
}
- (void)keyboardWillHide:(NSNotification *)notification {
NSDictionary *userInfo = [notification userInfo];
NSNumber *durationTime = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
[UIView animateWithDuration:durationTime.floatValue animations:^{
}completion:^(BOOL finished) {
UIEdgeInsets insets = self.tableView.contentInset;
insets.bottom = 0.0;
self.tableView.contentInset = insets;
}];
}
网友评论