表视图中的开关

Switches in Tableviews

我有以下习惯UITableViewCell

我希望我的视图控制器在有人翻转单元格的开关以更新我的模型时得到通知。我已经尝试使用 table 视图的委托方法(didSelectdidFinishEditingdidHighlight 等),但其中的 none 是在执行此操作时调用的。有什么办法可以做我想做的事吗?有人请帮忙。

实际上您的 UISwitch 已添加到 UITableViewCellaccessoryView,所以请在 cellforRowAtIndex

上点赞
var switchView = UISwitch(frame: CGRect.zero)
aCell.accessoryView = switchView
lightSwitch.tag = indexPath.row
switchView.setOn(false, animated: false)
switchView.addTarget(self, action: #selector(switchChanged(_:), for: .valueChanged)

并得到 UISwitch 的动作为

func switchChanged(_ sender: UISwitch) {

    print("which switch is \(sender.tag)")
    print("The switch is \(sender?.on ? "ON" : "OFF")")
}

要在有人翻转单元格开关时更新您的模型,您需要:

  1. 将单元格的 @IBAction func onSwitched(_ sender: UISwitch) 分配为 UISwitch Value Changed 侦听器,如此屏幕截图所示

  2. 将颜色模型附加到单元格

    cell.myColorModel = myColorModels[indexPath.row]

  3. @IBAction func onSwitched(_ sender: UISwitch)中简单地改变selected属性在模型

    @IBAction func onSwitched(_ sender: UISwitch) { myColorModel.selected = sender.isOn }

完整源代码

class MyColorModel {  

    var title: String!
    var color: UIColor!
    var selected: Bool = false

    init(title: String, color: UIColor) {
        self.title = title
        self.color = color
    }
}

class MyColorCell: UITableViewCell {

    @IBOutlet weak var colorTitle: UILabel!
    @IBOutlet weak var colorImage: UIImageView!
    @IBOutlet weak var colorSwitch: UISwitch!

    var myColorModel: MyColorModel! {
        didSet {
            colorTitle.text = myColorModel.title
            colorImage.backgroundColor = myColorModel.color
            colorSwitch.isOn = myColorModel.selected
        }
    }

    @IBAction func onSwitched(_ sender: UISwitch) {
        myColorModel.selected = sender.isOn
    }

}

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    fileprivate var myColorModels = [MyColorModel(title: "Red", color: UIColor.red),
                                 MyColorModel(title: "Green", color: UIColor.green),
                                 MyColorModel(title: "Blue", color: UIColor.blue)]


    @IBAction func onColorsCheck(_ sender: AnyObject) {
        for myColorModel in myColorModels {
            print("color \(myColorModel.title) \((myColorModel.selected) ? "is checked":"is not checked")")
        }
    }

    // MARK: - UITableView datasource & delegate

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myColorModels.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MyColorCell") as! MyColorCell

        cell.myColorModel = myColorModels[indexPath.row]

        return cell
    }
}