Search code examples
swiftnsuserdefaultsuibackgroundcolor

Changing main view controller background color from value in NSUserDefaults


I have two view controllers, one is the main one and the second is a settings view controller. I have buttons on the settings VC that is set to change the background color of the settings VC and the main one. It stores the color in NSUserDefaults so I can access it in the main view controller. Below is the code for the settings VC:

let defaults = NSUserDefaults.standardUserDefaults()

@IBAction func red(sender: AnyObject) {
    view.backgroundColor = (UIColor.redColor())
    NSUserDefaults.standardUserDefaults().setObject("red", forKey: "backColor")
    NSUserDefaults.standardUserDefaults().synchronize()

}
@IBAction func green(sender: AnyObject) {
    view.backgroundColor = (UIColor.greenColor())
    NSUserDefaults.standardUserDefaults().setObject("green", forKey: "backColor")
    NSUserDefaults.standardUserDefaults().synchronize()

}
@IBAction func black(sender: AnyObject) {
    view.backgroundColor = (UIColor.blackColor())
    NSUserDefaults.standardUserDefaults().setObject("black", forKey: "backColor")
    NSUserDefaults.standardUserDefaults().synchronize()

I'm new with Swift and don't know how to change/save the main VC's background color based on what is stored in NSUserDefaults from the pressed button. Can someone please help me?


Solution

  • In viewWillAppear of your main view controller, read the value from NSUserDefaults and set the view's backgroundColor property based upon the value of the string:

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
    
        let defaults = NSUserDefaults.standardUserDefaults()
    
        // Start color off with a default value       
        var color = UIColor.grayColor()
    
        if let backColor = defaults.objectForKey("backColor") as? String {
            switch backColor {
                case "red": color = UIColor.redColor()
                case "green": color = UIColor.greenColor()
                case "blue": color = UIColor.blueColor()
                case "black": color = UIColor.blackColor()
                default: break
            }
        }
    
        view.backgroundColor = color
    }