在表视图中选择和取消选择行时发出执行功能

时间:2019-09-17 04:58:05

标签: swift uitableview

注意:TableJSON是使用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

如何将其实现到自定义类中?

2 个答案:

答案 0 :(得分:0)

您应该尝试使用didSelectRowAt()和didDeselectRowAt()方法。假设这里允许多个选择,这就是我的做法。

如果选择了单元格

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

如果未选中单元格

override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    structure = sections[indexPath.section].items
    let theStructure = structure[indexPath.row]
    tappedSelected = theStructure.codeNum
    unselect(tappedSelected)
}

答案 1 :(得分:0)

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

首先,在您的closure中创建一个CheckableTableViewCell,并在true/false方法中使用setSelected(_: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中,通过handler方法为CheckableTableViewCell实例设置tableView(_: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()方法的问题。

对于您的另一个要求,请说明您要在什么时候将codeNum的值设置为tappedSelected。在tappedSelectedViewControllerCheckableTableViewCell的位置。

相关问题