tableView:indexPathForCell返回nil

tac*_*cos 38 iphone protocols uiwebview uitableview

我正在使用该方法tableView:indexPathForCell来实现自定义委托,该委托可以UITableViewCell根据其UIWebView内部的框架大小动态调整大小.问题是当我试图找出特定单元格的indexPath是什么时tableView:indexPathForCell返回nil:

- (void)trialSummaryTableViewCell:(TrialSummaryTableViewCell *)cell shouldAssignHeight:(CGFloat)newHeight {
    NSIndexPath *indexPath = [tableV indexPathForCell:cell];
    NSLog(@"tableV: %@\ncell: %@\nindexPath: %@", tableV, cell, indexPath); //<-- 
    // ...
}
Run Code Online (Sandbox Code Playgroud)

这里,tableV不返回nil,单元格不返回nil,但indexPath返回nil.

我究竟做错了什么?

编辑:我-(void)trialSummaryTableViewCell从该tableView:cellForRowAtIndexPath:方法调用

Jor*_*rez 124

可能是此时细胞不可见.tableView:indexPathForCell在这种情况下返回nil.我使用indexPathForRowAtPoint解决了这个问题,即使单元格不可见,此方法也能正常工作.代码:

UITableViewCell *cell = textField.superview.superview;
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:cell.center];
Run Code Online (Sandbox Code Playgroud)

  • 好答案!:)只是一个提示:`textField.superview.superview`是非常糟糕的设计,尽量避免这种情况. (7认同)

Nan*_*r R 13

如果单元格不可见,[tableV indexPathForCell:cell]返回nil.

此外,如果从"cellForRowAtIndexPath"方法调用"trialSummaryTableViewCell",您也可以轻松地将indexPath传递给"trialSummaryTableViewCell"方法.

  • 但它不会在ios <4.3上返回nil (2认同)

Dan*_*iel 5

一个小更新,因为 Jorge Perez 的答案将从 iOS7 开始失败(因为 aUIScrollView已插入并且呼叫textField.superview.superview将不再工作)。

NSIndexPath您可以这样检索:

//find the UITableViewCell superview
UIView *cell = textField;
while (cell && ![cell isKindOfClass:[UITableViewCell class]])
    cell = cell.superview;

//use the UITableViewCell superview to get the NSIndexPath
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:cell.center];
Run Code Online (Sandbox Code Playgroud)