之前項(xiàng)目中用到tableview的多選操作,今天梳理總結(jié)一下
要實(shí)現(xiàn)tableview的多選操作有很多種方式.有系統(tǒng)提供的方法,也可以自己通過其他方式實(shí)現(xiàn)同樣的效果.
第一種,我們使用自己的方式實(shí)現(xiàn)多選操作,先看一下效果:

效果一.gif
- 這是我們通過自己的方式實(shí)現(xiàn)cell的多選效果,首先創(chuàng)建一個(gè)Array用于存儲(chǔ)或者移除選中cell的IndexPath,在didSelectRowAtindexPath中判斷cell是否選中:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let index = selectedCellArray.index(of: indexPath) {
selectedCellArray.remove(at: index)
}else{
selectedCellArray.append(indexPath)
}
//刷新該行cell
self.testTableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
}
- 然后在cellForRowAtindexPath中實(shí)現(xiàn)選中和取消選中的效果:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var testCell = tableView.dequeueReusableCell(withIdentifier: "testCell")
if testCell == nil {
testCell = UITableViewCell.init(style: .default, reuseIdentifier: "testCell")
}
//判斷cell是否被選中
if selectedCellArray.contains(indexPath) {
testCell?.accessoryType = .checkmark
}else{
testCell?.accessoryType = .none
}
testCell?.textLabel?.text = "\(dataArray[indexPath.row])"
return testCell!
}
第二種,通過系統(tǒng)提供的方式實(shí)現(xiàn),就不需要自己創(chuàng)建array來(lái)存儲(chǔ)選中的cell.
- 首先,設(shè)置tableview的allowsMultipleSelection屬性為true
- 在didSelectRowAtindexPath中直接添加選中效果:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)!
cell.accessoryType = .checkmark
}
- 在didDeselectRowAtindexPath中取消選中效果:
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)!
cell.accessoryType = .none
}
第三種,在編輯狀態(tài)下,實(shí)現(xiàn)多選,刪除操作:

效果二.gif
這個(gè)實(shí)現(xiàn)起來(lái)比較簡(jiǎn)單:
- 設(shè)置tableview的是否允許編輯屬性allowsMultipleSelectionDuringEditing為true
_thirdTableView.allowsMultipleSelectionDuringEditing = true
- 選中的cell都會(huì)以IndexPath的方式保存在一個(gè)集合中,通過tableview的indexPathsForSelectedRows屬性直接取出這個(gè)集合
selecteds = _thirdTableView.indexPathsForSelectedRows
- 在刪除的方法中,刪除選中的cell即可
UITableView的多選不難,這里只是講了幾個(gè)關(guān)鍵的地方,如果有哪里不明白的可以點(diǎn)擊這里下載Demo