UITableView scrollToRowAtIndexPath不适用于最后4
我在UITableViewController中,我有单元格内的文本字段。 当用户点击文本字段时,我实现了UITextFieldDelegate,并在方法textFieldDidBeganEditing中确定单元格的索引并滚动到该位置。 它适用于最后4-5个单元的所有单元。 我究竟做错了什么? 谢谢。
scrollToRowAtIndexPath:方法只有在tableView的contentSize足够大才能将单元格移动到这些位置时,才会将单元格滚动到UITableViewScrollPositionTop或UITableViewScrollPositionMiddle 。 如果要滚动到顶部或中间的单元格是最后一个单元格或最后几个单元格中的任意一个,则不能将其滚动到中间或顶部。 在这些情况下,您需要为这些单元格手动计算contentOffset 。
编辑 – 计算contentOffset:
为了计算contentOffset,使用@Schoob指定的方法。 将下面的代码放在textFieldDidBeginEditing方法中。
CGPoint origin = textField.frame.origin; CGPoint point = [textField.superview convertPoint:origin toView:self.tableView]; float navBarHeight = self.navigationController.navigationBar.frame.size.height; CGPoint offset = tableView.contentOffset; // Adjust the below value as you need offset.y += (point.y - navBarHeight); [tableView setContentOffset:o animated:YES];
我发现使用scrollToRowAtIndexPath的关键是确保在视图呈现之后调用它。 即推到导航控制器或模态地提出。
我的工作代码是这样的
调用代码
MyViewController *cont = [[MyViewController alloc] initWithMedication:medication]; cont.sectionToShow = 1; [self.navigationController pushViewController:cont animated:YES]; [cont release];
viewWillAppear中的Viewcontroller代码
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:self.sectionToShow]; [cont.tableview scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
如果我以其他方式做了,总会有一些不起作用的边缘案例。 我想我们想在展示周期的后期滚动。
这是当你试图确定在UITableViewCell上添加的view / textField的indexPath时应该使用的
CGPoint point = [textField.superview convertPoint:textField.frame.origin toView:self.tableView];
然后使用点
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:point];