編輯模式
1. editButtonItem
self.navigationItem.rightBarButtonItem = editButtonItem
//配合editButtonItem
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
self.tableView.setEditing(editing, animated: true)
}
2.左滑刪除
直接實(shí)現(xiàn)下面的方法
實(shí)現(xiàn)的方法
//設(shè)置哪些行可以編輯
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
if(indexPath.row == 0){
return false
}else{
return true
}
}
// 設(shè)置單元格的編輯的樣式
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return UITableViewCell.EditingStyle.delete
}
//設(shè)置點(diǎn)擊刪除之后的操作
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
workManager.updateCollection(withYear: yearForSearch, month: monthForSearch, row: indexPath.row - 1)
count = count - 1
tableView.deleteRows(at: [indexPath], with: .fade)
tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
其中count - 1是因?yàn)閚umberOfRowsInSection這里返回了count,必須要count - 1 否則會報(bào)錯Invalid update,意思是刪除前后 數(shù)量應(yīng)該對應(yīng),count不減1的話數(shù)量不對。
其它方法
多個按鈕
editActionsForRowAtIndexPath
能設(shè)置出現(xiàn)編輯的按鈕 默認(rèn)是刪除 可以自定義UITableViewRowAction
可以設(shè)置多個操作,操作完tableView.editing = False 退出編輯模式
多選
allowsMultipleSelectionDuringEditing