Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shouldn't UISwitch work the opposite way?

I'm confused over why my code works in the opposite way than I originally thought it would. Below is how my code currently functions:

//MARK: Actions
@IBAction func SwitchTap(sender: UISwitch) {
    if mySwitch.on {                           //prints on if turning on
        mySwitch.setOn(true, animated: true)
        print ("switch is on")
    }
    else {
        mySwitch.setOn(false, animated: true)
        print("switch is off")              //prints off if turning off
    }

This is how I think it should work:

//MARK: Actions
@IBAction func SwitchTap(sender: UISwitch) {
    if mySwitch.on {
        mySwitch.setOn(**false**, animated: true) // should be false instead of true like in the previous example
        print ("switch is on")
    }
    else {
        mySwitch.setOn(**true**, animated: true) //should be true instead of false like in the previous example
        print("switch is off")
    }

I don't understand why the first version works but the second one doesn't. SetOn should turn the switch off when passed false as the first argument. Instead it is turning it off when passed true and simply doesn't change states.

like image 205
Jacob Avatar asked Jan 27 '26 20:01

Jacob


1 Answers

Recall that UISwitch toggles its value on end-user's tap.

Your SwitchTap gets invoked together with the switch togging its value internally. Your first code leaves the state the same, so when the switch toggles it, the end result is a toggle. Your second code, however, inverts the state, so when `UISwitch' toggles it, the switch stays in its original state, because two toggles cancel each other.

Removing all calls to setOn will fix your code.

like image 66
Sergey Kalinichenko Avatar answered Jan 30 '26 14:01

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!