2 problems with dealing with UITextField behind Keyboard
在我的视图中,我的UITableViewCell中有一个UITextField。现在有可能UITextField可以在我的键盘后面,所以我使用以下两种方法正确处理它。一个用于点击键盘,另一个用于解除键盘时:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | - (void)keyboardNotification:(NSNotification*)notification { CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size; CustomCell *cell = (CustomCell*)[[tempTextField superview] superview]; CGRect textFieldRect = [cell convertRect:tempTextField.frame toView:self.view]; if (textFieldRect.origin.y + textFieldRect.size.height >= [UIScreen mainScreen].bounds.size.height - keyboardSize.height) { thetableView.contentInset = UIEdgeInsetsMake(0, 0, keyboardSize.height, 0); NSIndexPath *pathOfTheCell = [thetableView indexPathForCell:cell]; [thetableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:pathOfTheCell.row inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES]; } } - (void)keyboardhideNotification:(NSNotification*)notification { thetableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0); } |
现在它运作得有点好,但有2个问题。
2
。当键盘位于键盘下方并且桌面视图向上滚动时,它会以一种漂亮的动画方式进行,但是当我点击完成时它会立即弹回到旧位置。我可以清楚地看到为什么会发生这种情况,但是如何让漂亮的动画恢复到tableview所处的旧位置?
任何投入将不胜感激!
更新:我设法找到#1的问题。这是一个愚蠢的错误。应该已将textField的高度添加到原点,因为该测量值正在向下。现在进入#2 ......
此代码只修复了1和2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | - (void)keyboardNotification:(NSNotification*)notification { CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size; CustomCell *cell = (CustomCell*)[[tempTextField superview] superview]; CGRect textFieldRect = [tempTextField convertRect:tempTextField.frame toView:self.view]; if (textFieldRect.origin.y + textFieldRect.size.height >= [UIScreen mainScreen].bounds.size.height - keyboardSize.height) { NSDictionary *info = [notification userInfo]; NSNumber *number = [info objectForKey:UIKeyboardAnimationDurationUserInfoKey]; double duration = [number doubleValue]; [UIView animateWithDuration:duration animations:^{ thetableView.contentInset = UIEdgeInsetsMake(0, 0, keyboardSize.height, 0); }]; NSIndexPath *pathOfTheCell = [thetableView indexPathForCell:cell]; [thetableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:pathOfTheCell.row inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:YES]; } } - (void)keyboardhideNotification:(NSNotification*)notification { NSDictionary *info = [notification userInfo]; NSNumber *number = [info objectForKey:UIKeyboardAnimationDurationUserInfoKey]; double duration = [number doubleValue]; [UIView animateWithDuration:duration animations:^{ thetableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0); }]; } |