从 ViewController 调用时如何设置应用程序的 UIWindow 颜色
How to set an app's UIWindow color when calling it from ViewController
在应用委托中,可以设置应用的 UIWindow
颜色,如代码所示。
但是,当尝试将应用程序的 UIWindow
颜色设置为 ViewController
中的其他颜色时,例如对 self.window?.backgroundColor = UIColor.blueColor()
的调用将被忽略。没有发生错误,但也没有发生颜色变化。
问题:
1 - 在 ViewController
中调用时如何设置应用程序的 window 颜色?
注意:我不是要更改视图背景颜色,而是要更改视图后面的 UIWindow
颜色。
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.window?.backgroundColor = UIColor.redColor()
return true
}
}
尝试通过您的 AppDelegate
或 UIApplication
类:
访问 window
if let window = (UIApplication.sharedApplication().delegate?.window)! as UIWindow! {
window.backgroundColor = UIColor.redColor()
}
或
if let window = UIApplication.sharedApplication().windows.first as UIWindow! {
window.backgroundColor = UIColor.redColor()
}
对于Objective-C,您可以使用此代码:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// your code
[UIApplication sharedApplication].delegate.window.backgroundColor = [UIColor yourColor];
return YES;
}
Swift 5:
if let window = UIApplication.shared.delegate?.window as? UIWindow {
window.backgroundColor = .red
}
在应用委托中,可以设置应用的 UIWindow
颜色,如代码所示。
但是,当尝试将应用程序的 UIWindow
颜色设置为 ViewController
中的其他颜色时,例如对 self.window?.backgroundColor = UIColor.blueColor()
的调用将被忽略。没有发生错误,但也没有发生颜色变化。
问题:
1 - 在 ViewController
中调用时如何设置应用程序的 window 颜色?
注意:我不是要更改视图背景颜色,而是要更改视图后面的 UIWindow
颜色。
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.window?.backgroundColor = UIColor.redColor()
return true
}
}
尝试通过您的 AppDelegate
或 UIApplication
类:
if let window = (UIApplication.sharedApplication().delegate?.window)! as UIWindow! {
window.backgroundColor = UIColor.redColor()
}
或
if let window = UIApplication.sharedApplication().windows.first as UIWindow! {
window.backgroundColor = UIColor.redColor()
}
对于Objective-C,您可以使用此代码:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// your code
[UIApplication sharedApplication].delegate.window.backgroundColor = [UIColor yourColor];
return YES;
}
Swift 5:
if let window = UIApplication.shared.delegate?.window as? UIWindow {
window.backgroundColor = .red
}