【问题标题】:Delete tableView row删除 tableView 行
【发布时间】:2013-12-20 07:25:06
【问题描述】:

我有一个包含自定义单元格的动态 tableView,例如,如果它的值为 0,我想删除一些单元格。

这是我的tableView:cellForRowAtIndexPath 方法:

{
    NSString *CellIdentifier;
    UITableViewCell *cell;

    if (indexPath.row == 0){
        CellIdentifier = @"adress cell";
        CustomAdressCell *cell = [detailsTableView dequeueReusableCellWithIdentifier:CellIdentifier];

       if (cell == nil) {
            NSArray *objects = [[NSBundle mainBundle] loadNibNamed:@"CustomTimeCell" owner:self options:nil];
            cell = [objects lastObject];
        }
        cell.someValue = self.someVal;

      return cell;
    }

    else if (indexPath.row == 1){
        CellIdentifier = @"phone cell";
        CustomPhoneCell *cell = [detailsTableView dequeueReusableCellWithIdentifier:CellIdentifier];

        if (cell == nil) {
            NSArray *objects = [[NSBundle mainBundle] loadNibNamed:@"CustomPhoneCell" owner:self options:nil];
            cell = [objects lastObject];
        }

        indexPathTest = indexPath;//index path for delete
        cell.someValue = self.someVal2;

        return cell;
    }
...
    else return cell;
}

例如:如果我在第二行有cell.someValue = 0,我需要删除这一行。我怎样才能做到这一点?谢谢!

编辑:在使用以下代码(自定义方法)在另一个 VC 中初始化我的 tableView 后,我试图删除行:

        [self.detailsTableView beginUpdates];
        [self.detailsTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPathTest]
                         withRowAnimation:UITableViewRowAnimationFade];
        [self.detailsTableView endUpdates];

我有错误:

Invalid update: invalid number of rows in section 0.  The number of rows contained in an 
existing section after the update (4) must be equal to the number of rows contained in that  
section before the update (4), plus or minus the number of rows inserted or deleted from that   
section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that 
section (0 moved in, 0 moved out).'

其他一些对我没有帮助的问题:

【问题讨论】:

    标签: ios iphone objective-c uitableview


    【解决方案1】:

    每当someValue 设置为 0 时,您可能需要删除该行。例如,将删除作为将其设置为 0 的任何进程的一部分,而不是根据一些随机事件抽象地做出反应。点击“0”按钮或输入0并关闭键盘,然后检查新值是否为0。如果是,则删除该行,如果不是,则不执行任何操作。

    您还可以设置一个计时器,以便每隔 X 秒循环一次并在必要时删除它们,但这样效率会低很多。

    无论哪种方式,您都可能只使用标准的deleteRowsAtIndexPaths:withRowAnimation: 方法。具体请查看UITableView documentation,了解有关该方法的更多详细信息。

    【讨论】:

      【解决方案2】:

      请注意,tableview 是与其关联的数组的图形表示(根据您的要求)。话虽这么说,当您从表视图中删除一行时,您应该从数组中删除该行/对象,以及您用于构造表视图的行/对象。如果不这样做,您最终会遇到 tableview 和数组反映不同状态的情况(这正是错误告诉您的内容)。

      【讨论】:

        猜你喜欢
        • 2016-12-25
        • 2012-06-19
        • 2012-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-28
        • 2014-04-29
        相关资源
        最近更新 更多