显示键盘时的iOS UITableView contentOffset
我正在尝试设置keyboard
出现时tableView
的contentOffset
。 实际的代码是在一个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; }];