How to change the function a UISwitch does based on which cell that UISwitch is in

Viewed 35

I'm going to try to make my attempt make sense in writing.

I used code rather than the storyboard for the tableview cells and uiswitch. The number of cells is based on count. How do I select what happens when the value changes for a uiswitch that is inside the different cells.

I feel like I need the function didselectrow but I don't know how to access it's uiswitch. As you can see in the handleswitchaction function each uiswitch does the action.

class SettingsCell: UITableViewCell {
    
    lazy var switchControl: UISwitch = {
        let switchControl = UISwitch()
        switchControl.isOn = true
        switchControl.onTintColor = UIColor(red: 55/255, green: 130/255, blue: 250/255, alpha: 1)
        switchControl.translatesAutoresizingMaskIntoConstraints = false
        switchControl.addTarget(self, action: #selector(handleSwitchAction), for: .valueChanged)
        return switchControl
    }()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        addSubview(switchControl)
        switchControl.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
        switchControl.rightAnchor.constraint(equalTo: rightAnchor, constant: -12).isActive = true
    }
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            //fatalError("init(coder:)  has not been implemented")
        }
    
    @objc func handleSwitchAction(sender: UISwitch) {
        if sender.isOn {
            print("Is on")
        } else {
            print("Is off")
        }
    }

}
2 Answers

Inside your dequeueReusableCell(withIdentifier:for:) add tag to your cell

settingsCell.switchControl.tag = indexPath.row

And use it inside handleSwitchAction as

switch(sender.tag) {
case 0: // First row
case 1: // Second row
// ...
}

Tag property is available in any UIView: https://developer.apple.com/documentation/uikit/uiview/1622493-tag

You can just switch indexPath.row without tags if your content is static in cell for row at:

switch indexPath.row {
   case 0:
   ...
}

or if it is dynamic you need to get some properties from backend to know how to handle.

Related