1

I am trying to have a switch appear in the off state once a view loads. Not always, but only if a boolean value that I created("switchBool") is false.

I've tried using the two ways on the apple documentation website. The two ways are shown in my code example. One is commented out.

import UIKit

class ViewController: UIViewController {

    var switchBool = false

    @IBAction func switchControl(_ sender: UISwitch) {

      //sender.isOn = switchBool

        sender.setOn(switchBool, animated: true)

    }

    override func viewDidLoad() {
        super.viewDidLoad()

    }


}

The app is building and running without errors. However, I want the switch to be in the off state if "false" is assigned to the bool "switchBool", which in my example it is, but no matter what I try the switch always appears in the on state when the view loads up.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Moe
  • 13
  • 3
  • You need an IBOutlet for your switch and then in viewDidLoad, call `switch.setOn(switchBool, animated: false)` – Don Jun 10 '19 at 22:34
  • The code you posted only sets the switch off when the user changes the switch to either on or off. – rmaddy Jun 10 '19 at 22:49
  • The position of the switch will be whatever you had set it in the Storyboard (unless you also set it in onViewDidLoad as said above). Your switchControl() function will only get called when the user actually moves the position of the switch. So, either set the default value in the Storyboard, or, call your switchControl(switchBool, mySwitch) method from your onViewDidLoad override to initialize it at startup. – Michael Dougan Jun 10 '19 at 23:32

2 Answers2

3

You need to create an IBOutlet for your switch(using the assistant editor button and storyboard). Then, you can just set the switch to be off in viewDidLoad:

override func viewDidLoad() {
    super.viewDidLoad()

    yourSwitch.setOn(switchBool, animated: true)
}
Xcoder
  • 1,433
  • 3
  • 17
  • 37
0

In the storyboard you can set it to be off in the Attribute inspector

SwiftiSwift
  • 7,528
  • 9
  • 56
  • 96