自ios7以来,indexPathForCell返回零

自ios7以来,indexPathForCell返回零,ios,objective-c,uitableview,ios7,Ios,Objective C,Uitableview,Ios7,我的应用程序在ios6.1下运行良好。已尝试ios7模拟器,但以下部分不起作用: EditingCell *cell = (EditingCell*) [[textField superview] superview]; NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; NSLog(@"the section is %d and row is %d", indexPath.section, indexPath.row

我的应用程序在ios6.1下运行良好。已尝试ios7模拟器,但以下部分不起作用:

EditingCell *cell = (EditingCell*) [[textField superview] superview];
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
NSLog(@"the section is %d and row is %d", indexPath.section, indexPath.row);
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];
NSString *rowKey = [[keysForRows objectAtIndex: section] objectAtIndex: row];
它总是来:

the section is 0 and row is 0
尽管选择了另一个节/行。 有人知道为什么这在ios7下不起作用吗?

您查找文本字段的“封闭”表视图单元格的方法很脆弱, 因为is假定一个固定的视图层次结构(在 iOS 6和iOS 7)

一种可能的解决方案是在视图层次结构中向上遍历,直到找到表视图单元:

UIView *view = textField;
while (view != nil && ![view isKindOfClass:[UITableViewCell class]]) {
    view = [view superview];
}
EditingCell *cell = (EditingCell *)view;
一种完全不同但常用的方法是用行“标记”文本字段 编号:


然后在文本字段delegate methods中使用该标记。

我正在以与您相同的方式查找单元格。现在,如果我在单元格中有一个按钮,并且知道我所在的tableview,我就使用这个快速方法。它将返回tableviewcell

-(UITableViewCell*)GetCellFromTableView:(UITableView*)tableView Sender:(id)sender {
    CGPoint pos = [sender convertPoint:CGPointZero toView:tableView];
    NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:pos];
    return [tableView cellForRowAtIndexPath:indexPath];
}

在iOS 11中遇到了这个问题,但在9或10中没有遇到,我使用@drexel sharp之前详细介绍的技术重写了
func indexath(对于cell:UITableViewCell)->indexath?
方法:

override func indexPath(for cell: UITableViewCell) -> IndexPath? {
    var indexPath = super.indexPath(for: cell)
    if indexPath == nil { // TODO: iOS 11 Bug?
        let point = cell.convert(CGPoint.zero, to: self)
        indexPath = indexPathForRow(at: point)
    }
    return indexPath
}

你们验证过textfield.superview.superview是类编辑单元吗?单元格的视图层次结构可能已更改。
[[textField superview]superview]
引用任何内容都是非常糟糕的方式。我按原样获得了应用程序。。我想让它在iOS 7下运行。如何验证编辑单元格是否属于类?(我对ios开发非常陌生…)要了解您的单元格的类别,请尝试
NSLog(@“单元格类别:%@”,NSStringFromClass(cell.class))您可能还需要查看UITableView方法ìndexPathOfSelectedCell`。希望这有帮助。很好,这很有效(第一个解决方案)。有什么需要关心的吗?或者这是正常的(或一种正常的)方式?有一种情况下,使用标记可能不起作用。如果您在表视图中有peforms-insertRowsAtIndexPaths的代码,标记将与indexPath.row不匹配。@PaulHeller:它应该在所有可见的单元格上匹配,因为它总是在cellForRowAtIndexPath中更新,但您是对的,您的反对也会使标记方法看起来很脆弱。如果该行滚动到视图之外,superview可以返回nil,让您处于无限状态loop@BradThomas:我假设在单元格内控件的委托/操作方法中,单元格是可见的。但是你永远不知道,添加一个nil超级视图的检查肯定应该完成(添加到答案中)。谢谢你的反馈!这肯定是答案。在视图层次上传递的越少越好。谢谢!工作起来很有魅力!无论出于何种原因,当indexPathForCell返回nil时,效果都非常好。在iOS 8上验证
override func indexPath(for cell: UITableViewCell) -> IndexPath? {
    var indexPath = super.indexPath(for: cell)
    if indexPath == nil { // TODO: iOS 11 Bug?
        let point = cell.convert(CGPoint.zero, to: self)
        indexPath = indexPathForRow(at: point)
    }
    return indexPath
}