iosswiftuiwindow

How to set an app's UIWindow color when calling it from ViewController


In the App delegate, it is possible to set an app's UIWindow color as seen in the code.

However, when trying to set an app's UIWindow color to a different color in the ViewController, a call for example to self.window?.backgroundColor = UIColor.blueColor() gets ignored. No errors occur, but no color change occurs either.

Question:

1 - How can I set an app's window color when calling it in the ViewController? Note: I'm not trying to change a View background color, but the UIWindow color which sits behind a View.

class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        self.window?.backgroundColor = UIColor.redColor()

        return true

    }

}

Solution

  • Try accessing the window through your AppDelegate or UIApplication classes:

        

    if let window = (UIApplication.sharedApplication().delegate?.window)! as UIWindow! {
        window.backgroundColor = UIColor.redColor()
    }
    

    or

    if let window = UIApplication.sharedApplication().windows.first as UIWindow! {
        window.backgroundColor = UIColor.redColor()
    }