override func preferredStatusBarStyle() -> UIStatusBarStyle {
 return UIStatusBarStyle.LightContent;
}

使用上述代码在任何ViewController中为特定的ViewController设置状态栏颜色为白色,在iOS8中对我来说是行不通的。有什么建议吗?使用UIApplication。shared应用方法,在信息中需要更改后颜色更改。Plist为整个应用程序。

// Change the colour of status bar from black to white
UIApplication.sharedApplication().statusBarStyle = .LightContent

我怎么能改变一些必要的和特定的视图控制器的状态栏颜色?


当前回答

Swift 3.0升级

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        UIApplication.shared.statusBarStyle = .lightContent

        return true
    }

其他回答

适用于基于导航的应用

    var addStatusBar = UIView()
    addStatusBar.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 20);
    addStatusBar.backgroundColor = global().UIColorFromRGB(0x65b4d9)
    self.window?.rootViewController?.view .addSubview(addStatusBar)

请在“didFinishLaunchingWithOptions launchOptions:”Appdelegate类中使用此代码

UIApplication.shared.statusBarStyle = .lightContent let statusBar: UIView = UIApplication.shared.value(forKey: "statusBar") as! UIView if statusBar.responds(to: #selector(setter: UIView.backgroundColor)){ statusBar.backgroundColor = UIColor.black }

iOS 13

 var statusBarView: UIView = UIView()
        if #available(iOS 13.0, *) {
            let tag:UInt64 = 38482458385
            if let statusBar = UIApplication.shared.keyWindow?.viewWithTag(Int(tag)) {
                statusBar.backgroundColor = UIColor.red
                statusBarView = statusBar
            } else {
                let statusBar = UIView(frame: UIApplication.shared.statusBarFrame)
                statusBar.tag = Int(tag)
                UIApplication.shared.keyWindow?.addSubview(statusBar)
                statusBarView = statusBar
            }
        } else {
            statusBarView = (UIApplication.shared.value(forKey: "statusBar") as? UIView)!
            if statusBarView.responds(to: #selector(setter: UIView.backgroundColor)){
                statusBarView.backgroundColor = UIColor.red
            }
        }

对于Xcode 10,你可以创建一个类并把它放在你的viewController类之前,你可以在所有视图控制器中调用这个类,需要一个轻内容状态栏…

class UIViewControllerWithLightStatusBar: UIViewController {
override var preferredStatusBarStyle: UIStatusBarStyle {
return UIStatusBarStyle.lightContent
}
}

现在在下面修改你的viewController类:

class YourViewController: UIViewControllerWithLightStatusBar {
...
}

这就是全部……

在你的信息。plist你需要将基于视图控制器的状态栏外观定义为任何值。

如果你定义它为YES,那么你应该在每个视图控制器中重写preferredStatusBarStyle函数。

如果你定义它为NO,那么你可以在AppDelegate中使用

UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true)

(截至2021年10月25日)

Swift 5, Swift 4.2, Swift 4

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    setNeedsStatusBarAppearanceUpdate()
}
override var preferredStatusBarStyle: UIStatusBarStyle {
    .lightContent
}