Search code examples
iosswiftuiviewcontrollerappdelegateuibackgroundcolor

Swift: Setting ViewController background color from AppDelegate


I want to change my ViewController's background color. Within the view controller, I can write self.view.backgroundColor = UIColor (red: 0, green: 0.0, blue: 0.5, alpha: 1.0). However, I need to change it from AppDelegate. According to this answer, accessing properties of the ViewController in AppDelegate works like this:

1) Setting a global variable: var myViewController: ViewController!

2)

var theViewController = ViewController()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.myViewController = theViewController

So that

self.myViewController.view.backgroundColor = UIColor (red: 0, green: 1.0, blue: 0.5, alpha: 1.0)

should change the background color. However, it doesn't. How can I change the ViewController's background color from AppDelegate?


Solution

  • You are creating a new instance of the view controller with var theViewController = ViewController(), and you store the new instance in the global variable you set up, but that instance is never used anywhere.

    What you want is the view controller instance used by the app. I'm not sure how you app view hierarchy is set up, but you probably want to get the root view controller for you app.

    In the AppDelegate class you can try

    theViewController = self.window?.rootViewController
    theViewController.view.backgroundColor = UIColor (red: 0, green: 1.0, blue: 0.5, alpha: 1.0)