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

怎甘沉沦 提交于 2021-01-28 19:15:20

问题


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

    }

}

回答1:


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()
}



回答2:


For Objective-C you can use this code:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // your code
    [UIApplication sharedApplication].delegate.window.backgroundColor = [UIColor yourColor]; 

    return YES;
}



回答3:


Swift 5:

if let window = UIApplication.shared.delegate?.window as? UIWindow {
    window.backgroundColor = .red
}


来源:https://stackoverflow.com/questions/35920020/how-to-set-an-apps-uiwindow-color-when-calling-it-from-viewcontroller

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!