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

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


当前回答

我可以给你一个更简单的方法,

就像苹果文档说的那样,在viewDidLoad中调用setNeedsStatusBarAppearanceUpdate,

如果视图控制器的状态栏属性(如隐藏/不隐藏状态或样式)发生变化,则调用此方法。如果在动画块中调用此方法,则更改将与动画块的其余部分一起动画化。

实现preferredStatusBarStyle返回您的首选类型。

我在iOS 10.1系统中使用了这个功能。

Objective - C

[self setNeedsStatusBarAppearanceUpdate];

-(UIStatusBarStyle)preferredStatusBarStyle {
     return UIStatusBarStyleLightContent;
}

斯威夫特

setNeedsStatusBarAppearanceUpdate()

var preferredStatusBarStyle: UIStatusBarStyle { 
    return .lightContent
}

我很惊讶没有人指出这一点。无论如何,喜欢:)

其他回答

截至2020年10月,Swift 5, Xcode 12

如果你想把它设置为应用中的所有视图控制器如果你的应用有导航控制器。

你可以在plist文件中这样做,如下所示:

斯威夫特3

在你的AppDelegate文件中的func application方法中

let statusBar: UIView = application.value(forKey: "statusBar") as! UIView
statusBar.backgroundColor = .red

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

您可以在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]

点击支持文件组(左边顶部-项目名称)。单击“信息”。点击列表之间的+,就像下面的bundle name。并添加“基于视图控制器的状态栏外观”并将其设置为NO。 然后打开AppDelegate.swift,像这样修改:

func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {

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

return true
}

这是它。

自定义状态栏颜色(iOS11+, Swift4+)

如果您正在寻找如何将状态栏更改为自定义颜色的解决方案,这是可行的解决方案。

let statusBarView = UIView()
view.addSubview(statusBarView)
statusBarView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
    statusBarView.topAnchor.constraint(equalTo: view.topAnchor),
    statusBarView.leftAnchor.constraint(equalTo: view.leftAnchor),
    statusBarView.rightAnchor.constraint(equalTo: view.rightAnchor),
    statusBarView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor)
])
statusBarView.backgroundColor = .blue