通过TableView的编辑模式切换快速删除行

2022-03-05  本文已影响0人  alanhoo74

在TableView中,可以通过切换其编辑模式,给用户提供删除数据行的操作,如下图,进入该模式后,点击“红色减号”完成删除(当然需要对应的删除Model中的数据项)


屏幕快照 2022-03-05 上午11.49.13.png

首先需要启动TableView的编辑模式,通过如下代码完成:

tableViewController.tableView.setEditing(true, animated:true)

如果是通过Navigation BarItem的类似Edit的按钮启动的,可以将其标题改为Done,提示用户完成删除时点击此按钮。

用户真正删除的时候,在TableViewController对应的delegate事件中,执行数据的删除操作和视图操作:

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
            dataModel.removeItem(at: indexPath.row+1)
            tableView.deleteRows(at: [indexPath], with: .automatic)
    }
}

如果用户完成了期望的所有删除操作,则将TableView的Editing修改为false

tableViewController.tableView.setEditing(false, animated:true)

以上就简单的删除表格行的操作。

上一篇 下一篇

猜你喜欢

热点阅读