动态添加和删除UITableViewCells到UITableView

Rap*_*eta 3 iphone uitableview ios4

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

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

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

在此先感谢您的帮助!

don*_*kim 7

类似于Derek上面所说的 - UITableViewController已经提供了删除行的功能.

要切换编辑a 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;
}
Run Code Online (Sandbox Code Playgroud)

也覆盖 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];
    }   
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!