Bram Roelandts
Bram Roelandts

Reputation: 470

UISwitch not changing value in Swift

I'm using this little function in my Swift 2.2 app:

func changeSwitchValue() {


    if self.lampValue == 1 {
        self.switch0.setOn(true, animated: false)
        print("changed to 1")
    }
    if self.lampValue == 0 {

        self.switch0.setOn(false, animated: true)
        print("changed to 0")
    }
}

When the function is called, it prints everything out I asked, but the switch value never changes!

I tried using switch0.setOn(true, animated:true) in the ViewDidLoad and it worked there. When called by this function, it doesn't work . If I called this chunk of code by an IBAction, it doesn't work either..

Does anyone know something about this weird issue? Any advice?

Thank you!

Upvotes: 2

Views: 1162

Answers (2)

Christian Dietrich
Christian Dietrich

Reputation: 11868

make sure you do the ui actions back on the main thread

    dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) { () -> Void in
        // do the networking here
        // if you are done update the ui on the main thread
        dispatch_async(dispatch_get_main_queue()
            ) { () -> Void in
                self.mySwitch.setOn(!self.mySwitch.on, animated: true)
        }
    }

Upvotes: 5

Kristin Harkness
Kristin Harkness

Reputation: 82

You have not posted enough code, but I will assume that switch0 is a UISwitch which is in a nib, and is declared in a view controller like this:

@IBOutlet weak var switch0: UISwitch!

If that is not the case, all bets are off :) So my feedback is, are you sure switch0 is wired to the correct outlet in the nib?

Upvotes: -2

Related Questions