自ios7以来,indexPathForCell返回nil
我的应用程序在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
尽pipeselect了另一个部分/行。 有人有一个想法,为什么这不工作在ios7下?
你find文本字段的“封闭”表格视图单元格的方法是脆弱的,因为它假设了一个固定的视图层次结构(在iOS 6和iOS 7之间似乎已经改变了)。
一种可能的解决scheme是在视图层次结构中遍历直到find表视图单元格:
UIView *view = textField; while (view != nil && ![view isKindOfClass:[UITableViewCell class]]) { view = [view superview]; } EditingCell *cell = (EditingCell *)view;
一个完全不同但常用的方法是用行号“标记”文本字段:
cell.textField.tag = indexPath.row; // in cellForRowAtIndexPath
然后在文本字段委托方法中使用该标签。
我以同样的方式寻找细胞。 现在我使用这个快速方法,如果我有一个单元格中的button,并知道我所在的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,我覆盖了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 }