I have added a switch along with each cell in table view but the switch function is not get called. If I give the switch in the front page its displaying successfully. But in tableview cell its not working `
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
}
}
`
CodePudding user response:
The signature is wrong. There must be a space character between the underscore and sender
. And if it's not a real IBAction replace @IBAction
with @objc
@objc func switchValueDidChange(_ sender: UISwitch) {
if sender.isOn {...
and – not related to the issue – the selector can be simply written
#selector(switchValueDidChange)