How to call an action when UISwitch changes state?

Ondrej picture Ondrej · Dec 21, 2011 · Viewed 40.8k times · Source

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.

Answer

mac picture mac · Dec 21, 2011
[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);
}