问题
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