TheIOSCoder TheIOSCoder - 4 months ago 22
iOS Question

How to check the state of an UISwitch from another ViewController in SWIFT 3?

I want to check the State of an

UISwitch
from another
View Controller
. And if the
switch
is
on
, then I want the
backgroundColor
of the
View
to be red, otherwise it should be green. I tried to use
UserDefaults
, but I have no idea what to start with. Any help would be greatly appreciated!

Answer

NOTE: THIS IS THE VERSION FOR SWIFT 3:

First of all, I've set the initial state of the switch to off. I have added a button, which leads us to the secondViewController and also checks the state of the switch. Here is my code(for the View Controller which contains the switch):

    @IBOutlet weak var switch1: UISwitch!
        let defaults = UserDefaults.standard
        var switchON : Bool = false
@IBAction func checkState(_ sender: AnyObject) {

        if switch1.isOn{
            switchON = true
        defaults.set(switchON, forKey: "switchON")
        }
        if switch1.isOn == false{
            switchON = false
            defaults.set(switchON, forKey: "switchON")
        }

    }

And for the secondView:

let defaults = UserDefaults.standard

    override func viewDidLoad() {
        super.viewDidLoad()
        if defaults.value(forKey: "switchON") != nil{
            let switchON: Bool = defaults.value(forKey: "switchON")  as! Bool
            if switchON == true{
                self.view.backgroundColor = UIColor.red()
            }
            else if switchON == false{
                self.view.backgroundColor = UIColor.green()
            }
        }
    }

Main.storyboard

Hope this helps!