首页 > 解决方案 > 在表格视图中选择和取消选择行时发出执行功能

问题描述

注意:TableView 使用 JSON 填充,其结构包含值 codeNum

我需要根据是否选择或取消选择行来执行两个不同的功能,以下是我现有的选择机制:

class CheckableTableViewCell: UITableViewCell {
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.selectionStyle = .none
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        self.accessoryType = selected ? .checkmark : .none
    }
}

选择行时select()需要运行,未选择行时unselect()需要运行。在此之前,需要将行 codeNum 值分配给变量 tappedSelected:

    structure = sections[indexPath.section].items
    let theStructure = structure[indexPath.row]
    tappedSelected = theStructure.codeNum

这如何实现到自定义类中?

标签: swiftuitableview

解决方案


您可以使用闭包在选择/取消选择单元格时调用方法。

首先,closure在你的中创建一个并用in方法CheckableTableViewCell调用它,即true/falsesetSelected(_:animated:)

class CheckableTableViewCell: UITableViewCell {
    var handler: ((Bool)->())? //here....

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        self.accessoryType = selected ? .checkmark : .none
        handler?(selected) //here....
    }

    //rest of the code....
}

接下来,在您的 中ViewController,设置例如方法中的handlerCheckableTableViewCelltableView(_:cellForRowAt:)

 class VC: UIViewController, UITableViewDataSource {
    //rest of the code...

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CheckableTableViewCell
        cell.handler = {[weak self](selected) in
            selected ? self?.select(indexPath) : self?.unselect()
        }
        return cell
    }

    func select(_ indexPath: IndexPath) {
        let structure = sections[indexPath.section].items
        let theStructure = structure[indexPath.row]
        tappedSelected = theStructure.codeNum
    }

    func unselect() {
        //add the code here...
    }
}

这将解决您在选择或取消选择单元格时调用select()unselect()方法的问题。

对于您的另一个要求,请说明您想在什么时候将codeNumvalue 设置为tappedSelected. 并且在哪里tappedSelected存在,在ViewController或在CheckableTableViewCell


推荐阅读