Search code examples
objective-cioscocoa-touchuiswitch

How to prevent a UISwitch from changing state?


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.


Solution

  • set the state of UISwitch to off in xib and inside valueChange action method

    -(IBAction) switchValueChanged{
    if (toggleSwitch.on) { 
        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];
    }
    }