19

my app was running fine under ios6.1. tried the ios7 simulator and the following part does not work:

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];

It always comes:

the section is 0 and row is 0

although another section / row were selected. Has someone an idea why this does not work under ios7?

4

3 回答 3

30

您查找文本字段的“封闭”表格视图单元格的方法很脆弱,因为它假定了一个固定的视图层次结构(这似乎在 iOS 6 和 iOS 7 之间发生了变化)。

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

UIView *view = textField;
while (view != nil && ![view isKindOfClass:[UITableViewCell class]]) {
    view = [view superview];
}
EditingCell *cell = (EditingCell *)view;

一种完全不同但经常使用的方法是用行号“标记”文本字段:

cell.textField.tag = indexPath.row;   // in cellForRowAtIndexPath

然后只需在文本字段委托方法中使用该标记。

于 2013-09-11T14:20:26.230 回答
22

我和你一样找到细胞。现在,如果我在单元格中有一个按钮并且知道我所在的表格视图,我会使用这种快速方法。它将返回表格视图单元格。

-(UITableViewCell*)GetCellFromTableView:(UITableView*)tableView Sender:(id)sender {
    CGPoint pos = [sender convertPoint:CGPointZero toView:tableView];
    NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:pos];
    return [tableView cellForRowAtIndexPath:indexPath];
}
于 2013-09-19T14:49:41.077 回答
0

在 iOS 11 中遇到这个问题,但在 9 或 10 中没有,我func indexPath(for cell: UITableViewCell) -> IndexPath?使用 @drexel-sharp 之前详述的技术覆盖了该方法:

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
}
于 2017-11-06T14:36:57.893 回答