获取单元格或文本字段在这个单元格中的位置

我有一个拆分视图控制器:视图和表格视图。 在这个表格视图我有自定义单元格与文本字段。 我不知道会有多less个细胞,所以会自动生成。 现在我想滚动到文本框,当它成为FirstResponder。 我试过这样的事情:

-(void) textFieldDidBeginEditing:(UITextField *)textField { CGPoint focusOnTextField = CGPointMake(0, 300 + textField.frame.origin.y); [scroller setContentOffset: focusOnTextField animated: YES]; } 

300px – 我的TableView的开始位置。 所有似乎bounds.origin.y ,但textField.frame.origin.y总是等于0(像和bounds.origin.y btw)。

我以为我可以解决一个问题,如果获取单元格的位置,哪个文本字段处于活动状态,然后replacecell.frame.origin.y textField.frame.origin.y或类似的东西。

================================================== =================

我忘了说,我的tableviews滚动被禁用。 我遵循你的build议和代码示例,并解决它:

 - (UITableViewCell *)cellWithSubview:(UIView *)subview { while (subview && ![subview isKindOfClass:[UITableViewCell self]]) subview = subview.superview; return (UITableViewCell *)subview; } - (void)textFieldDidBeginEditing:(UITextField *)textField { UITableViewCell *activeCell = [self cellWithSubview:textField]; float offsetValueY = 200 + activeCell.origin.y; CGPoint focusOnTextField = CGPointMake(0, offsetValueY); [scroller setContentOffset:focusOnTextField animated:YES]; } 

知道什么? 它正在工作! :-)但是它创造了一个新问题。 当我开始编辑textfield的时候,scroller首先跳到顶部,然后才到正确的位置。 当我写[scroller setContentOffset:focusOnTextField animated:NO]; 这个问题消失了,但是没有滚动的顺利。 而这对我来说是不好的:-)那我们该如何解决呢?

以下是如何滚动到包含文本字段的单元格…

 // find the cell containing a subview. this works independently of how cells // have been constructed. - (UITableViewCell *)cellWithSubview:(UIView *)subview { while (subview && ![subview isKindOfClass:[UITableViewCell self]]) subview = subview.superview; return (UITableViewCell *)subview; } 

您的想法是正确的,以便在编辑开始时触发该操作。 只要用细胞做…

 - (void)textFieldDidBeginEditing:(UITextField *)textField { // find the cell containing this text field UITableViewCell *cell = [self cellWithSubview:textField]; // now scroll using that cell's index path as the target NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES]; } 

如果您在UITableVieCell内容视图中添加文本字段(如果使用的是.xib,则默认添加),那么您必须调用类似于textField.superview.superview东西,这会为您提供父级单元格。 如果直接将文本字段添加到单元格视图,则必须使用textField.superview

 [tableView scrollToRowContainingComponent:textField atScrollPosition: UITableViewScrollPositionMiddle animated:YES]; 

在将以下类别添加到UITableView之后:

 @implementation UITableView (MyCategory) -(NSIndexPath*)indexPathOfCellComponent:(UIView*)component { if([component isDescendantOfView:self] && component != self) { CGPoint point = [component.superview convertPoint:component.center toView:self]; return [self indexPathForRowAtPoint:point]; } else { return nil; } } -(void)scrollToRowContainingComponent:(UIView*)component atScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animated { NSIndexPath *indexPath = [self indexPathOfCellComponent:component]; if(indexPath) { [self scrollToRowAtIndexPath:indexPath atScrollPosition: scrollPosition animated:animated]; } } @end