6

我有一个 UITableView,里面有自定义单元格。此自定义单元格看起来像样式为“Detail Left”的普通单元格。但我的自定义单元格有一个详细标签和一个文本字段,以允许用户编辑文本。我有一个保存按钮,我想保存用户输入的所有数据。我使用本教程制作了自定义单元格:http: //agilewarrior.wordpress.com/2012/05/19/how-to-add-a-custom-uitableviewcell-to-a-xib-file-objective-c/ #comment-4883

为了获取用户数据,我将文本字段的委托设置为表视图控制器(self)并实现了 textFieldDidEndEditing: 方法。在这种方法中,我询问文本字段的父视图(= 单元格)并询问此单元格的 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);
...
}

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

4

2 回答 2

5

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

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

现在它工作正常!

于 2012-10-12T12:58:28.233 回答
0

您可以在 CustomCell 中添加一个属性并在里面index填充它吗indexPath.row(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

于 2012-10-12T12:15:30.537 回答