UITableView:indexPathForCell返回nil

38

我正在使用方法tableView:indexPathForCell实现自定义代理,根据其中的UIWebView框架大小,动态调整UITableViewCell的大小。问题是当我尝试查找特定单元格的indexPath时,tableView:indexPathForCell返回nil

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

在这里,tableV 不返回 nil,cell 也不返回 nil,但是 indexPath 返回了 nil

我做错了什么?

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


我认为当你从cellForRowAtIndexPath调用**-(void)trialSummaryTableViewCell**时,单元格尚未被创建。 - Paul Warkentin
@qPaul:所以cell不会返回nil,因为它是一个实例变量,但如果它没有被添加到tableView中,它将没有indexPath? - tacos_tacos_tacos
是的,我想是这样,但也有可能是错误的。 - Paul Warkentin
3个回答

129

可能此时该单元格不可见。tableView:indexPathForCell在这种情况下返回nil。我使用了indexPathForRowAtPoint解决了这个问题,即使单元格不可见,该方法也能起作用。代码如下:

UITableViewCell *cell = textField.superview.superview;
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:cell.center];

非常感谢!我完全不理解正在发生什么,以及为什么有时候运行,有时候又不行。但有趣的是,即使单元格处于不可见状态,这也能起作用,而对于我来说,这是一个问题所在:我会插入自定义单元格,开始编辑文本字段,滚动并将焦点放在另一个文本字段上,此时就会触发结束编辑,但我却无法获得索引路径。返回并编辑第一个字段,并再次尝试相同的操作将正常工作。 - kos
7
好的回答! :) 只是一个提示:textField.superview.superview 是一个非常糟糕的设计,请尽量避免使用。 - the_critic
出于好奇,当单元格在视图之外时,为什么这个方法能够正常工作(我不清楚单元格中心点和表视图边界之间的关系)? - Bradley Thomas
这是确切的解决方案。 - Mohit Manhas
@Koen textField.center 返回的是其父视图系统中的坐标,而不是tableview/collectionview中的坐标,因此不是正确的坐标。很可能这会导致tableview/collectionview始终返回row/item=1,section=1。 - Kevin R
显示剩余5条评论

13

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

此外,如果您从“cellForRowAtIndexPath”方法调用“trialSummaryTableViewCell”,您也可以轻松地将indexPath传递到“trialSummaryTableViewCell”方法中。


2
但是它在 iOS < 4.3 上不会返回 nil。 - nverinaud

5

一个小更新,因为Jorge Perez的答案在iOS7及以上版本中将会失败(因为UIScrollView被插入,并且调用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];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接