2

我将 tableview 与可重复使用的单元格一起使用。在每个单元格上,我都有一个带有文本的 textField,我可以对其进行修改。如果文本为空,我删除该单元格。

假设我们有 100 行,我们想要修改第 1 行:我们点击它,给出一个空字符串 @"",向下滚动到第 50 位并点击这个单元格。

现在发生的事情是我们检测到另一个单元格上的点击手势,我调用方法 textFieldDidEndEditing: 来查看我是否应该从 tableview 中删除这个单元格。我使用 cellForRowAtIndexPath: 来获取修改后的单元格。

问题是出现了其他带有空文本字段的单元格。我删除了修改过的单元格,但只有一个。我认为这是可重复使用细胞的问题。

有人可以帮我解决这个问题吗?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ImageIdentyfier = @"StandardCellWithImageIdentifier";

    StandardCellWithImage *cellImage = (StandardCellWithImage *)[tableView dequeueReusableCellWithIdentifier:ImageIdentyfier];

    if(cellImage == nil) {
        cellImage = [[StandardCellWithImage alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ImageIdentyfier];
    }
    cellImage.nameLabel.delegate = self;
    Item *item  = [self.mutableFetchResults objectAtIndex:indexPath.row];
    cellImage.nameLabel.text = item.itemText;
    cellImage.infoLabel.text = item.itemInfo;
    cellImage.checkbox.userInteractionEnabled = YES;
    cellImage.nameLabel.userInteractionEnabled = NO;
    if(item.itemIsChecked.boolValue == YES) {
        cellImage.checkbox.tag = indexPath.row;
        [cellImage.tapGesture addTarget:self action:@selector(didSelectedImageAtIndexPath:)];
        cellImage.checkbox.image = [UIImage imageNamed:@"checkbox-checked.png"];
    } else {
        cellImage.checkbox.tag = indexPath.row;
        [cellImage.tapGesture addTarget:self action:@selector(didSelectedImageAtIndexPath:)];
        cellImage.checkbox.image = [UIImage imageNamed:@"open-checkbox.png"];
    }
    return cellImage;
}
4

2 回答 2

1

当您从第 1 行滚动到第 50 行时,已存在的单元格将被重用 - 包括您的单元格与空文本字段。这就是为什么您多次看到它以及为什么您的删除例程只删除了一个而不是全部。

听起来您在cellForRowAtIndexPath方法中创建的单元格需要修复以确保不会将空文本字段自动复制到回收的单元格中。没有看到任何代码,这个练习留给你。

看了代码,thanx。看不到任何“简单”的修复,所以建议你应该避免这个问题。因此,也许您应该检查列表滚动,而不是检查单元格的点击。

您存在的问题只是因为正在编辑的单元格由于用户滚动列表而被回收。因此通过 a) 不要让用户在编辑文本时滚动或 b) 在用户开始滚动时停止文本编辑来解决问题。

于 2013-02-06T09:54:32.373 回答
1

当你textFieldDidEndEditing被调用完成时,你应该检查文本是否是""如果是""我认为你应该从dataSource然后删除它reloadData

你的- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath方法应该这样写:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    XXXXXXXCell *cell = [tableView dequeueReusableCellWithIdentifier: kIdentifier];
    if (cell == nil) {

        //Init cell, only init

    }

    //Setup the cells detail, such as the textField.text and so on

    return cell;

}
于 2013-02-06T10:05:38.817 回答