0

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.

dhruveonmars
  • 409
  • 1
  • 11
  • 24

1 Answers1

1

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)
        }
    }
}
Allanah Fowler
  • 1,251
  • 16
  • 17
  • Thanks! That worked :) Though, I also use similar code as I mentioned in the question to change the background color of a button in the same function and that works. It does get me wondering why it doesn't work with the UISwitch though – dhruveonmars Feb 03 '16 at 23:11
  • I would say that since there is more than one view with that tag, the function returns the first one it finds, and not necessarily the one you are after. – Allanah Fowler Feb 03 '16 at 23:16
  • Hmm... I was under the impression that my code was getting all UISwitch items within the view with the tag, `sender.tag`. Because all the UISwitch items are created within a for loop and within that for loop, the tag is added when created, and it does print the correct tag whenever you click on the switch or button – dhruveonmars Feb 03 '16 at 23:21
  • The code `viewWithTag` only returns one view, and if there is more than one view with the tag you are looking for, then you might not get the one you want. In your case it was probably picking up the button rather than the switch, since they have the same tag. Using a for loop as above makes sure that you are checking all views, rather than stopping at one. – Allanah Fowler Feb 03 '16 at 23:29
  • Ah, ok. Thanks for clearing that up. Would you recommend I change my code in other places from what I had to what you answered? – dhruveonmars Feb 03 '16 at 23:32
  • If there is only one view with the tag you are looking for then `viewWithTag` is fine because you are guaranteed to get the right view. However, if there is a chance that another view will be picked up because it has the same tag as the one you want, then it would be best to change it. – Allanah Fowler Feb 03 '16 at 23:36