Chris Hutchison Chris Hutchison - 7 months ago 56
iOS Question

How to call a UISwitch touch without using IBaction/InterfaceBuilder

I am trying to call a function whenever my UISwitch is tapped without using an @ib action but am having trouble finding the proper way to do this nothing is seeming to work no matter how i try to call it. I am using everything through code and not storyboard so using an ib property isn't really an option i am trying to use at going about this

I am using this but keep getting the error

terminating with uncaught exception of type NSException

func gameSwitchTapped(){
if gameMuteSwitch.isOn == true {
gameview.saveData.set(false, forKey: gameview.gameMuteKey)
} else {
gameview.saveData.set(true, forKey: gameview.gameMuteKey)}

And, elsewhere:

gameMuteSwitch.addTarget(self, action: Selector(("gameSwitchTapped")), for: UIControlEvents.valueChanged)


I think this should do it:

mySwitch.addTarget(self, action: #selector(self.switchChanged(sender:)), forControlEvents: UIControlEvents.ValueChanged)

func switchChanged(sender: UISwitch) {
   let value = mySwitch.on
   // Do something