UITableView的indexPathForCell:始终返回0作为indexPath.row

tes*_*ter 6 objective-c uitableview nsindexpath

我有一个带有自定义单元格的UITableView.此自定义单元格看起来像样式为"细节左侧"的正常单元格.但我的自定义单元格有一个详细信息标签和一个文本字段,以允许用户编辑文本.我有一个保存按钮,我想保存用户输入的所有数据.我使用本教程编写了自定义单元格:http://agilewarrior.wordpress.com/2012/05/19/how-to-add-a-custom-uitableviewcell-to-a-xib-file-objective-c/ #评论- 4883

为了获取用户数据,我将文本字段的委托设置为表视图控制器(self)并实现了textFieldDidEndEditing:方法.在这个方法中,我要求文本字段的父视图(= cell)并请求该单元格的indexPath.问题是,无论我编辑什么单元格,我总是为indexPath.row得到0.我究竟做错了什么?

这是我的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:[CustomCell reuseIdentifier] forIndexPath:indexPath];
if (cell == nil) {
    [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
    cell = self.customCell;
    self.customCell = nil;
}

cell.label.text = @"Some label text";
cell.editField.delegate = self;
cell.accessoryType = UITableViewCellAccessoryNone;

return cell;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
CustomCell *cell = (CustomCell *) textField.superview;

NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];

NSLog(@"the section is %d and row is %d", indexPath.section, indexPath.row);
...
}
Run Code Online (Sandbox Code Playgroud)

编辑:我刚刚发现,返回的indexPath是零.所以,如果它是零我得到标准值0,那没关系.但是现在:为什么我为indexPath获取nil?

tes*_*ter 5

我自己就找到了解决方案.我在stackoverflow中找到了superview的代码,所以我只是复制了它.但这不起作用.你需要做两个这样的超级视图:

CustomCell *cell = (CustomCell *) textField.superview.superview;
Run Code Online (Sandbox Code Playgroud)

现在它工作正常!