Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 865
milesmeow Avatar asked Jan 02 '12 10:01

milesmeow


6 Answers

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.

like image 183
andrei Avatar answered Nov 01 '22 05:11

andrei


One unsophisticated solution is just putting a button with the same size and transparent background color in front of the UISwitch control. While it is not the direct answer to your question, it is nice workaround and I always do that with UIImageView.

like image 30
tia Avatar answered Nov 01 '22 07:11

tia


Why dont u simply set userInteraction to NO

[self.switchButton setUserInteractionEnabled:NO];
like image 30
yunas Avatar answered Nov 01 '22 07:11

yunas


add a clear color subview to that UISwitch view, cover it and add UITapGestureReconizer to this subview, and all action operations can be triggered in tap action including change the UISwitch view status. Hope it help you!

like image 3
user3818648 Avatar answered Nov 01 '22 05:11

user3818648


Try to listen to the TouchDown event instead of TouchUpInside.

like image 1
Manlio Avatar answered Nov 01 '22 05:11

Manlio


This is the way you do it, set UISwitch to .touchUpInside

switchBtn.addTarget(self, action: #selector(unlockEvent), for: .touchUpInside)

if you set to .valueChanged, will trigger the event every time, regardless having user interaction or not.

like image 1
JBarros35 Avatar answered Nov 01 '22 07:11

JBarros35