Done
Done

Reputation: 1088

Check UISwitch status on viewDidLoad

I am having problem with status of UISwitch at start. Why is my switch always in the on state?

@IBOutlet  weak var switch: UISwitch!

override func viewDidLoad() {
    super.viewDidLoad()

    if let sw = switch {
        if sw.on  {
            print("on")
        } else {
            print("off")
        }
    }
}

Upvotes: 0

Views: 235

Answers (1)

Mike Schmidt
Mike Schmidt

Reputation: 1065

The switch will be whatever you set it in the storyboard / interface builder. If you set it to on in the storyboard, it will always be on when the app first loads, and vice versa for setting it to off.

If you want to set it to off when your view first loads (programatically), regardless of what is set in the storyboard, use switch.on = false

If you want the switch's state to be saved when the app is closed, you should look into using NSUserDefaults (here)

Here is a screenshot of the state set in the storyboard:

enter image description here

Upvotes: 1

Related Questions