UISwitch 在添加 tableView 单元格时不调用该函数

UISwitch is not invoking the function when added with tableView cell

我在 table 视图中为每个单元格添加了一个开关,但未调用开关功能。如果我在首页中提供开关,则它会成功显示。但是在 tableview 单元格中它不起作用`

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.textLabel?.text = models[indexPath.row].Address
    cell.textLabel?.text = models[indexPath.row].Number
    cell.textLabel?.text = models[indexPath.row].Role
    cell.textLabel?.text = models[indexPath.row].Name
    
    //switch
    
    let mySwitch = UISwitch(frame: .zero)
    mySwitch.setOn(false, animated: true)
    mySwitch.tag = indexPath.row
    mySwitch.tintColor = UIColor.red
    mySwitch.onTintColor = UIColor.green
    mySwitch.addTarget(self, action: #selector(switchValueDidChange(_:)), for: .valueChanged)
    cell.accessoryView = mySwitch

    return cell
}

@IBAction func switchValueDidChange(_sender: UISwitch){

    if _sender .isOn{
        print("switch on")
        view.backgroundColor = UIColor.red         }
    else{
        view.backgroundColor = UIColor.systemPurple
    }
}
`

签名有误。下划线和 sender 之间必须有一个 space 字符。如果它不是真正的 IBAction,请将 @IBAction 替换为 @objc

@objc func switchValueDidChange(_ sender: UISwitch) {
    if sender.isOn {...

and – 与问题无关 – 选择器可以简单地写成

#selector(switchValueDidChange)