Search code examples
xcodeswiftuiswitchviewwithtag

Swift: Change UISwitch status when a button is clicked on with the same tag


I have this function which gets a UISwitch with the same tag value as the button that triggers the function, and it is then meant to change the status of the UISwitch to true:

let tagToSwitch = self.view.viewWithTag(sender.tag) as? UISwitch
tagToSwitch?.setOn(true, animated: true)

however this doesn't work, and if I change tagToSwitch! the app crashes and gives back the error 'fatal error: unexpectedly found nil while unwrapping an Optional value' though I'm not sure where I'm going wrong as when I print the sender.tag value before this, it prints the correct value.

Any help is appreciated.


Solution

  • viewWithTag might not be getting the view that you want. You could try a for loop instead.

    for view in self.view.subviews {
        if let tagToSwitch = view as? UISwitch {
            if tagToSwitch.tag == sender.tag {
                tagToSwitch.setOn(true, animated: true)
            }
        }
    }