首页 > 解决方案 > 在 UITableview 中删除一行时在底部插入新行

问题描述

我有一个要求,我需要始终显示一个三行的表格视图。

当用户滑动删除一行时,我需要在底部添加一个新行。

发生这种情况时,必须保留将行向左移动以删除的滑动动画。我的意思是删除动画不应该受到影响。这可能吗?

标签: iosxamarin.ios

解决方案


首先,您的方法dataSource必须始终返回 3 numberOfRows(in:)。然后您可以通过这种方式提交更改:

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        tableView.performBatchUpdates({

            // Delete the swiped row
            tableView.deleteRows(at: [indexPath], with: .left)
            // Get the last row index (numberOfRows-1)
            let lastRowIndex = tableView.numberOfRows(inSection: indexPath.section)-1
            // Insert a new row at the end
            tableView.insertRows(at: [IndexPath(row: lastRowIndex, section: 0)], with: .top)

        }, completion: nil)
    }
}

不要忘记dataSource相应地更新其余部分,因为单元格可能会被重复使用。代码需要在call之前performBatchUpdates添加。像这样的东西:

var cellsText = ["A","B","C"]

// Inside your tableView(:commit:forRowAt) method:

if editingStyle == .delete {
    cellsText.remove(at: indexPath.row)
    cellsText.append("D")

    // ...
}

推荐阅读