如何在 UITableViewCell 中使用 UISwitch?

问题描述

我正在尝试使用自定义 UITableViewCell 构建 UITableView。我以编程方式在 tableView cellForRowAt 函数中创建了一个 UISwitch。我如何知道根据 indexPath.row 切换哪个 UISwitch?在我下面的@objc func switchTapped() 中,我希望它打印如下内容:“在第 3 行切换”或“在第 3 行切换”。但是,无论我在 tableView 中的任何行上点击哪个开关,我得到的唯一打印结果都是“在行处切换:0 已打开”。

这告诉我: item.isOn = switchView.isOn == true ?真假 不起作用,因为 item.isOn 的值始终为真。

任何帮助将不胜感激。谢谢。

为了节省空间,我只在下面包含了函数 cellForRowAt。

class CustomTableCell: UITableViewCell {
    @IBOutlet weak var hourLabel: UILabel!
    @IBOutlet weak var minuteLabel: UILabel!
    @IBOutlet weak var ampmLabel: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        self.isUserInteractionEnabled = true
        self.selectionStyle = .none
    }
    override func setSelected(_ selected: Bool,animated: Bool) {
        super.setSelected(selected,animated: animated)
    }
}

class AlarmVC: UIViewController {
    @IBoutlet weak var tableView: UITableView!
    var item = SetAlarmCell()

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UINib(nibName: "AlarmTableCell",bundle: nil),forCellReuseIdentifier: "AlarmTableCell")
        loadItems()
    }
}

extension AlarmVC: UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "AlarmTableCell",for: indexPath) as! AlarmTableCell
        item = K.setAlarmCellArray[indexPath.row]
    
        let switchView = UISwitch(frame: .zero)
        switchView.seton(true,animated: true)
        switchView.tag = indexPath.row
        switchView.addTarget(self,action: #selector(switchTapped),for: .valueChanged)
        item.isOn = switchView.isOn == true ? true : false
        cell.accessoryView = switchView
    }

    @objc func switchTapped() {
        if item.isOn == true {
            print("Switch at row: \(K.rowTapped) is on")
        } else {
            print("Switch at row: \(K.rowTapped) is off")
        }
    }

}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)