How to call an action when UISwitch changes state?

IphoneIos5Uiswitch

Iphone Problem Overview


I want to perform some action when UISwitch changes its state, thus is set on or off. How do I do this? I need to pass two objects as parameters.

It's created in code, thus not using xib.

Iphone Solutions


Solution 1 - Iphone

[yourSwitchObject addTarget:self action:@selector(setState:) forControlEvents:UIControlEventValueChanged]; 

This will call the below method when your switch state changes

- (void)setState:(id)sender 
{
    BOOL state = [sender isOn];
    NSString *rez = state == YES ? @"YES" : @"NO";
    NSLog(rez);
}

Solution 2 - Iphone

Obviously we can do the same with Swift, here is the code (compiled and worked with the latest version of the Swift 3.1)

Add action to your switch button:

mySwitch.addTarget(self, action: #selector(self.switchValueDidChange), for: .valueChanged)

And implement this method:

@objc func switchValueDidChange(sender:UISwitch!) {
    print(sender.isOn)
}

Or even if you are not using the sender you may remove:

func switchValueDidChange() {
    // do your stuff
}

Solution 3 - Iphone

Easy solution for me (worked with swift 4):

@IBAction func toggleSwitch(_ sender: UISwitch) {
    if(mySwitch.isOn) {
        //Do something
    } else {
        //Do something
    }
}

Link the above function with value changed in Sent Events under connection tab

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOndrejView Question on Stackoverflow
Solution 1 - IphonemacView Answer on Stackoverflow
Solution 2 - IphoneMasihView Answer on Stackoverflow
Solution 3 - IphoneYWangView Answer on Stackoverflow