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 4或4.2中

你可以加上vc

preferredStatusBarStyle

并设置返回值为

.lightContent或.default

ex:

override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
}

其他回答

如果有人想改变状态栏的电池和文本颜色,如下图所示:

您可以在appdelegate类中使用以下代码。

UINavigationBar.appearance().barTintColor = UIColor(red: 234.0/255.0, green: 46.0/255.0, blue: 73.0/255.0, alpha: 1.0)
UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.white]

适用于swift4中基于特定视图控制器的导航

   let app = UIApplication.shared
   let statusBarHeight: CGFloat = app.statusBarFrame.size.height

   let statusbarView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: statusBarHeight))
   statusbarView.backgroundColor = UIColor.red
   view.addSubview(statusbarView)

在我的情况下,我使用故事板来组织我的视图控制器。我想改变所有的状态栏风格。

你可以在下面的图片中看到。

Stars View Controller是一个CPBaseNavigationController,而CPBaseNavigationController是UINavigationController的子类。

我试着做下面的步骤:

在AppDelegate.swift func didFinishLaunchingWithOptions中添加 //更改状态栏颜色 UIApplication.sharedApplication()。statusBarHidden = false UIApplication.sharedApplication()。statusBarStyle = .LightContent 但没有效果。 在StoryBoard中,找到Base Tab BarController(上图)。选择属性检查器,将状态条属性更改为轻内容。太糟糕了,没有效果。

最后我明白了。在我的自定义导航控制器CPBaseNavigationController中添加func preferredStatusBarStyle override func preferredStatusBarStyle() -> UIStatusBarStyle { 返回.LightContent } 它工作得很好!

此外,statusBarStyle在9.0中已弃用,你可以使用-[UIViewController preferredStatusBarStyle]。

实现preferredStatusBarStyle,如你所述,并调用self.setNeedsStatusBarAppearanceUpdate()在ViewDidLoad和 也在信息。设置UIViewControllerBasedStatusBarAppearance为YES(默认是YES)

目前还不清楚为什么它不起作用。我需要检查代码。另一个建议是 使用viewDidLoad UIApplication.sharedApplication()中的工作代码。statusBarStyle = . lightcontent,并将此更改为默认值,当您查看viewgetdisappear viewWillDisappear。

这里有十亿个答案,所以我想为什么不以扩展的形式添加另一个(在@ ceure的帮助下)

斯威夫特3

扩展:

extension UIApplication {
    class var statusBarBackgroundColor: UIColor? {
        get {
            return (shared.value(forKey: "statusBar") as? UIView)?.backgroundColor
        } set {
            (shared.value(forKey: "statusBar") as? UIView)?.backgroundColor = newValue
        }
    }
}

实现:

UIApplication.statusBarBackgroundColor = .blue