Detecting a change in UISwitch Detecting a change in UISwitch ios ios

Detecting a change in UISwitch

   -(void) createSwitch    {        self.searchExistSearchNewSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(0,0,0,0)];        [self.searchExistSearchNewSwitch addTarget:self action:@selector(switchValueChanged:) forControlEvents:UIControlEventValueChanged];        [self.view addSubview:self.searchExistSearchNewSwitch];    }    - (void)switchValueChanged:(UISwitch *)theSwitch    {        BOOL flag = theSwitch.isOn;    }

In iOS 11 a new UISwitch bug was introduced so I don't recommend subscribing to value changed events. Otherwise your callback will be triggered every time UISwitch's isOn attribute changes programmatically.


  1. Subscribe for touch up inside event:
let switch = UISwitch()switch.addTarget(self, action: #selector(onSwitchValueChanged), for: .valueChanged)
  1. Implement the callback method:
func onSwitchValueChanged(_ switch: UISwitch) {        }
  1. And now when you programmatically change isOn value, it won't trigger onSwitchValueChanged method.

switch.isOn = !switch.isOn // 'onSwitchValueChanged' is not triggered

Get state of switch in handler:

- (void)valueChanged:(UISwitch *)theSwitch {   BOOL flag = theSwitch.on;}