Use switch as global variable on multiple classes in Swift 4

I am trying to use a global variable to determine the background color of multiple classes. So if the switch in settingsViewController is on the background color should be red if it’s off it should be blue. I am also user defaults to try to save the value of the global var.

         var global = UserDefaults.standard.string(forKey: "sx")
    import UIKit

     class settingsViewController: UIViewController {

  var total = ""

   @IBOutlet var switchy : UISwitch!


   override func viewDidLoad() {
super.viewDidLoad()

       if global = 2{
      view.backgroundcolor = uicolor.red
    } else {
  view.backgroundcolor = uicolor.blue
       }


    }



  @IBAction func pressONorOff(){
if switchy.isOn == true {
    global = String(2)
 UserDefaults.standard.set("2", forKey: "sx")


} else {
    global = String(1)
    UserDefaults.standard.set("1", forKey: "sx")
}
  }}


  class twoVC: UIViewController {

 override func viewDidLoad() {
super.viewDidLoad()

       if global = 2{
      view.backgroundcolor = uicolor.red
    } else {
   view.backgroundcolor = uicolor.blue
       }}}

Hi @timswift,
maybe it is that when you typed the code here, you have an error, look at your if loops,

 if global = 2 {

This is invalid as you are trying to compare not assign, you would need

if global == 2 {

Secondly, you need to update the backgrounds of your views when you trigger the switch and change the values.

cheers,

Jayant

This topic was automatically closed after 166 days. New replies are no longer allowed.