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?
In
viewWillAppear
of your main view controller, read the value fromNSUserDefaults
and set the view'sbackgroundColor
property based upon the value of the string: