UITableView多选操作

2017-05-01  本文已影响334人  小心韩国人
之前项目中用到tableview的多选操作,今天梳理总结一下

要实现tableview的多选操作有很多种方式.有系统提供的方法,也可以自己通过其他方式实现同样的效果.

第一种,我们使用自己的方式实现多选操作,先看一下效果:
效果一.gif
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)
        
    }
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!
    }
第二种,通过系统提供的方式实现,就不需要自己创建array来存储选中的cell.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath)!
        cell.accessoryType = .checkmark
    }
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath)!
        cell.accessoryType = .none
    }
第三种,在编辑状态下,实现多选,删除操作:
效果二.gif

这个实现起来比较简单:

_thirdTableView.allowsMultipleSelectionDuringEditing = true
selecteds = _thirdTableView.indexPathsForSelectedRows

UITableView的多选不难,这里只是讲了几个关键的地方,如果有哪里不明白的可以点击这里下载Demo

上一篇 下一篇

猜你喜欢

热点阅读