显示键盘时的iOS UITableView contentOffset

我正在尝试设置keyboard出现时tableViewcontentOffset 。 实际的代码是在一个CustomTableView : UITableView <UIScrollViewDelegate> ,因为它在整个应用程序中被广泛使用,因此使用self作为tableView 。 我的代码如下所示:

 - (void)keyboadDidAppear:(NSNotification *)notification { NSTimeInterval animationDuration = [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]; CGRect keyboardBeginFrame = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue]; CGFloat keyboardHeight = CGRectGetHeight(keyboardBeginFrame); CGPoint contentOffset = self.contentOffset; originalContentOffset = self.contentOffset;//hold reference to reset it when keyboard is hidden contentOffset.y += keyboardHeight; [UIView animateWithDuration:animationDuration animations:^{ [self layoutIfNeeded]; } completion:^(BOOL finished) { if (finished) { [self setContentOffset:contentOffset animated:YES]; } }]; } 

问题在于,当用户点击tableView顶部附近的tableCell时,它总是按键盘的高度偏移内容,这是错误的。 理想情况下,我想要抵消的内容,所以窃听tableCell只是在键盘上方。 问题是我不知道该怎么做。 我有一个粗略的想法,我需要像这样的东西:

 distanceBetweenTappedCellAndTableBottom > keyboardHeight ? do nothing : offsetContentBy keyboardHeight + tappedCellHeight. 

任何build议,我怎么能拿出数字? 还是有更好的解决scheme?

稍后编辑:

我无法使用contentInset因为tableView具有sectionHeaders ,并且设置contentInset会导致sectionHeaders保持修复,而rows向上移动。

根据以下build议解决

 CGSize kbSize = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size; NSTimeInterval duration = [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]; CGFloat height = UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation]) ? kbSize.width : kbSize.height; height += 10.0;//it needs to be slightly higher so the textField is clearly visible. originalEdgeInset = self.contentInset; __weak typeof (self) block = self; [UIView animateWithDuration:duration animations:^{ UIEdgeInsets edgeInsets = block.contentInset; edgeInsets.bottom += height; block.contentInset = edgeInsets; edgeInsets = block.scrollIndicatorInsets; edgeInsets.bottom += height; block.scrollIndicatorInsets = edgeInsets; }]; 

我认为键盘不会移动,当您将键盘高度添加到edgeInset以及

  CGSize kbSize = [[[sender userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size; NSTimeInterval duration = [[[sender userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]; CGFloat height = UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation]) ? kbSize.width : kbSize.height; [UIView animateWithDuration:duration animations:^{ UIEdgeInsets edgeInsets = _generalTableView.contentInset; edgeInsets.bottom += height; _generalTableView.contentInset = edgeInsets; edgeInsets = _generalTableView.scrollIndicatorInsets; edgeInsets.bottom += height; _generalTableView.scrollIndicatorInsets = edgeInsets; }];