iOS tableview列表单/多选。

效果图.gif

常用的列表单多选,可以避免滑动带来的复用bug

界面基本布局代码

override func configueLayout() {
        let btn = UIButton.init()
        btn.setTitle("确定", for: .normal)
        btn.backgroundColor = .color1682247
        btn.layer.cornerRadius = 22
        btn.titleLabel?.font = .systemFont(ofSize: 17, weight: .medium)
        btn.addTarget(self, action: #selector(sureBtnClick), for: .touchUpInside)
        view.addSubview(btn)
        btn.snp_makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.bottom.equalToSuperview().offset(-44)
            make.height.equalTo(44)
        }
        
        view.addSubview(table)
        table.snp_makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.bottom.equalTo(btn.snp_top).offset(1)
        }
    }
    
    
    private lazy var table: UITableView = {
        let v = UITableView.init()
        v.delegate = self
        v.dataSource = self
        v.register(cellType: chooseStuCell.self)
        v.separatorInset = UIEdgeInsets.init(top: 0, left: 16, bottom: 0, right: -16)
        return v
    }()

在swift中,需要使用class修饰词。原因:浅拷贝

class chooseStuModel:HandyJSON {
    var isSelc: Bool = false
    
    required init() {}
}

关键代码

extension YXChooseStuVC: UITableViewDelegate, UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        dataArr.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(for: indexPath, cellType: chooseStuCell.self)
        cell.model = dataArr[indexPath.row]
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = dataArr[indexPath.row]
        model.isSelc = !model.isSelc
        tableView .reloadRows(at: [indexPath], with: .automatic)
    }
}

思路:

创建一个浅拷贝模型,OC中可以直接创建,在模型中自己创建一个布尔类型的值判断是否点击了cell。然后在didSelectRow中去赋值模型,然后刷新。通过模型控制界面,这样可以避免复用的bug

你可能感兴趣的:(iOS tableview列表单/多选。)