How to prevent a UISwitch from changing state?

milesmeow picture milesmeow · Jan 2, 2012 · Viewed 13.7k times · Source

I have a UISwitch that is defined in an .xib file. The event that I'm connected to is "Value Changed".

I want the following behavior (essentially warning the user that this function is available in the Full Vesion of the software):

  1. allow user to click on switch
  2. prevent the switch from sliding to "on" (I want the switch to stay in the "off" position)
  3. show an alert

So far, I can't get 2 to work. Right now I have a kludge. I force the switch to go back to the OFF position:

[self.switchButton setOn:NO animated:NO];

UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Feature unlocked in Full Version" message:nil delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil] autorelease];
alert.tag = ALERT_TAG;
[alert show];

The problem is that you see the switch slide to the ON position, then it jumps to the OFF position, and then you see the alert box.

Is there a way to intercept the behavior so that the switch doesn't slide to the ON position?

UPDATE

I tried to link up to the "TouchUpInside" event and have moved my alert code there. It's still not early enough to intercept the visual change in the state of the switch.

Answer

andrei picture andrei · Apr 7, 2016

I've had the same problem like you. In your valueChanged action method you have to invoke the setOn method with animated set to true. So in swift that would be:

@IBAction func switchValueChanged(sender: UISwitch) {
    sender.setOn(false, animated: true)
}

It might seem counterintuitive since this method is called after switch value changed. But somehow it seems to work.