key9060
key9060

Reputation: 75

UISwitch not turning off?

I have 3 switches. I want it so when one turns on the other 2 turn off.

My code currently looks like this.

if MPHSwitch.on {
        KPHSwitch.enabled = false
        MperSSwitch.enabled = false
    }

I simply want to turn off the switches but setting enabled to false greys them out.

I have tried KPHSwitch.off but that doesn't seem to work.

Upvotes: 0

Views: 692

Answers (1)

NSNoob
NSNoob

Reputation: 5608

Change your code to the following in your condition:

KPHSwitch.setOn(false, animated: true) //If you don't want animation, send animated parameter false
MperSSwitch.setOn(false, animated: true)

The problem is, you are using the wrong property here, When instead you should have used the setOn method.

From Apple Documentation on UISwitch:

setOn(_:animated:)

Set the state of the switch to On or Off, optionally animating the transition.

What you are doing is, you are changing operation ability of the UIControl i.e. Switch in this case.

From Apple Documentation on UIControl Class, this is what enabled does:

Set the value of this property to true to enable the control or false to disable it. An enabled control is capable of responding to user interactions, whereas a disabled control ignores touch events and may draw itself differently. Setting this property to false adds the UIControlStateDisabled flag to the control’s state bitmask; enabling the control again removes that flag.

You are making the UISwitch ignore touch events and that in turn makes it redraw itself which changes the color to grey.

So in your case, you have to use setOn.

Upvotes: 2

Related Questions