UITableView的indexPathForCell:方法总是返回0作为indexPath.row

6
我有一个带有自定义单元格的UITableView,该自定义单元格外观与样式“Detail Left”相同。但是我的自定义单元格具有详细标签和文本字段,以允许用户编辑文本。我有一个Save按钮,要保存用户输入的所有数据。我使用此教程制作了自定义单元格: http://agilewarrior.wordpress.com/2012/05/19/how-to-add-a-custom-uitableviewcell-to-a-xib-file-objective-c/#comment-4883 为了获取用户数据,我将文本字段的代理设置为表视图控制器(self),并实现了textFieldDidEndEditing:方法。在此方法中,我询问文本字段的父视图 (=单元格)并询问该单元格的indexPath。问题是,无论我编辑哪个单元格,我始终得到0作为indexPath.row。我做错了什么?
以下是我的代码:
- (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);
...
}

编辑:我刚刚发现,返回的indexPath是空的。如果它是空的,我会得到标准值0,这没问题。但现在问题来了:为什么我会得到空的indexPath?


这是一个类似的线程,解释了这个原因 https://dev59.com/Z2w05IYBdhLWcg3w72XN - Khaled Annajar
2个回答

5

我自己找到了解决方案。我在stackoverflow上找到了superview的代码,所以我只是复制了它。但那行不通。你需要像这样使用两个superviews:

CustomCell *cell = (CustomCell *) textField.superview.superview;

现在它运行良好!


0

你能否在CustomCell中添加一个index属性,并在(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath方法中将其填充为indexPath.row


好主意,我试过了,但是出现了一个错误,说“未识别的选择器发送到实例... [UITableViewCellContentView indexPath]”(我调用了属性indexPath)。所以,我有点困惑为什么cell现在是UITableViewCellContentView而不是我的CustomCell。 - tester

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