动态添加和删除UITableViewCells到UITableView

时间:2010-12-10 01:37:51

标签: iphone uitableview ios4

我正在构建一个应用程序,用户可以在其中提供他/她拥有的不同用户名。愿景是,用户可以添加和删除UITableViewCell以输入用户名。

现在我有一个分组的UITableView,在每个UITableViewCell的右侧,我有一个UIButton,它使用UITextField向表中添加另一个单元格。在第一个单元格之后,每个单元格都有一个删除按钮。我正在尝试让UIButton删除该行。我有删除单元格的IBAction,唯一的问题是,它没有删除正确的行。

做我想做的事情的最佳方法是什么?我不知道如何在Google上正确搜索此内容。我确信有人做了我想做的事。

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:7)

与Derek上面所说的相似 - UITableViewController已经提供了删除行的功能。

要切换UITableView的修改,请执行以下操作:[self.tableView setEditing:!self.tableView.editing animated:YES];

用类似的东西覆盖tableView:canEditRowAtIndexPath:(因为听起来你不希望第一行被删除):

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([indexPath row] == 0) {
            return NO;
    }

    return YES;
}

同时覆盖tableView:commitEditingStyle:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle 
forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [self.dataArray removeObjectAtIndex:[indexPath row] - 1];

        // delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
}

希望这有帮助!

答案 1 :(得分:2)

听起来您正在尝试编写表视图已有的代码。查看表视图的内置编辑工具,您会发现不需要将这些解开按钮作为表视图,并且委托具有内置的editwing工具。

您对删除错误内容的评论让我觉得您在将行号与源数据的索引匹配时存在问题。