在Swift中更改状态栏背景颜色3

在XCode 7.3.x中,我改变了我的StatusBar的背景颜色:

func setStatusBarBackgroundColor(color: UIColor) { guard let statusBar = UIApplication.sharedApplication().valueForKey("statusBarWindow")?.valueForKey("statusBar") as? UIView else { return } statusBar.backgroundColor = color } 

但是,这似乎不再适用于Swift 3.0。

我试着用:

 func setStatusBarBackgroundColor(color: UIColor) { guard let statusBar = (UIApplication.shared.value(forKey: "statusBarWindow") as AnyObject).value(forKey: "statusBar") as? UIView else { return } statusBar.backgroundColor = color } 

但它给了我:

 this class is not key value coding-compliant for the key statusBar. 

任何想法如何改变它与XCode8 / Swift 3.0?

 extension UIApplication { var statusBarView: UIView? { return value(forKey: "statusBar") as? UIView } } UIApplication.shared.statusBarView?.backgroundColor = .red 

“更改”状态栏背景颜色:

 let statusBarView = UIView(frame: UIApplication.shared.statusBarFrame) let statusBarColor = UIColor(red: 32/255, green: 149/255, blue: 215/255, alpha: 1.0) statusBarView.backgroundColor = statusBarColor view.addSubview(statusBarView) 

更改状态栏的文字颜色:

 override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } 

尝试这个

转到您的应用程序info.plist

  1. 将基于视图控制器的状态栏外观设置为NO
  2. 将状态栏样式设置为UIStatusBarStyleLightContent

然后转到您的应用程序委托并粘贴以下代码设置您的Windows的RootViewController。

 #define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending) if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) { UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width, 20)]; view.backgroundColor=[UIColor blackColor]; [self.window.rootViewController.view addSubview:view]; }