【问题标题】:Dynamically add and remove UITableViewCells to UITableView动态添加和删除 UITableViewCells 到 UITableView
【发布时间】:2010-12-10 01:37:50
【问题描述】:

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

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

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

提前感谢您的帮助!

【问题讨论】:

    标签: iphone uitableview ios4


    【解决方案1】:

    类似于 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];
        }   
    }
    

    希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      听起来您正在尝试编写表格视图已有的内容。查看表格视图的内置编辑工具,您会发现您不需要这些取消按钮,因为表格视图和委托具有内置的编辑功能。

      您关于删除错误内容的评论让我认为您在将行号与源数据的索引匹配时遇到了问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-26
        • 1970-01-01
        • 1970-01-01
        • 2013-02-19
        • 2012-11-19
        • 1970-01-01
        • 2017-06-23
        • 1970-01-01
        相关资源
        最近更新 更多