在TableView中信轿,可以通過切換其編輯模式隘庄,給用戶提供刪除數(shù)據(jù)行的操作旅敷,如下圖,進(jìn)入該模式后冬阳,點(diǎn)擊“紅色減號”完成刪除(當(dāng)然需要對應(yīng)的刪除Model中的數(shù)據(jù)項(xiàng))
屏幕快照 2022-03-05 上午11.49.13.png
首先需要啟動TableView的編輯模式蛤虐,通過如下代碼完成:
tableViewController.tableView.setEditing(true, animated:true)
如果是通過Navigation BarItem的類似Edit的按鈕啟動的,可以將其標(biāo)題改為Done肝陪,提示用戶完成刪除時點(diǎn)擊此按鈕笆焰。
用戶真正刪除的時候,在TableViewController對應(yīng)的delegate事件中见坑,執(zhí)行數(shù)據(jù)的刪除操作和視圖操作:
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)
以上就簡單的刪除表格行的操作捏检。