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 5或xcode 11及以后的版本中设置(查看基于控制器的状态栏外观)key In info。plist为NO 然后转到项目目标,选择通用,设置状态栏样式为深色或浅色

其他回答

斯威夫特3

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

这是为特定的视图控制器设置状态栏背景色的解决方案。

我遵循了这个教程,它对我很有效。然而,我不确定是否有任何警告。

https://coderwall.com/p/dyqrfa/customize-navigation-bar-appearance-with-swift

打开你的信息。Plist和set UIViewControllerBasedStatusBarAppearance设为false。 在AppDelegate.swift中的第一个函数中,它包含didFinishLaunchingWithOptions,设置你想要的颜色。

UIApplication.sharedApplication()。statusBarStyle = UIStatusBarStyle。LightContent

Swift 3更新* 共享。statusbarstyle = .lightContent

斯威夫特3

//
//  LoginController.swift
//  Swift 3
//
//  Created by The Crab on 17/01/2017.
//  Copyright © 2017 Paxi Labs. All rights reserved.
//

import UIKit

class LoginController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        setNeedsStatusBarAppearanceUpdate()

        view.backgroundColor = UIColor(red: 61/255, green: 91/255, blue: 151/255, alpha: 1)

    }

    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
}

我在Swift 5、Swift 4.2中使用这种方式。

在Info.plist中添加下一个值:

UIViewControllerBasedStatusBarAppearance = YES

or

UIViewControllerBasedStatusBarAppearance = NO(查看变化)

UIStatusBarHidden = NO

UIStatusBarStyle = UIStatusBarStyleDefault(或设置为UIStatusBarStyleLightContent,如果你想在启动时看到轻状态栏文本)

然后将代码放置到您想要看到浅色内容的特定视图控制器(要看到深色文本,请将preferredStatusBarStyle设置为. darkcontent)。

override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
}

override func viewDidLoad() {
    super.viewDidLoad()

    if let statusBar: UIView = UIApplication.shared.value(forKey: "statusBar") as? UIView {
        statusBar.backgroundColor = .sunflowerYellow
    }
}

另一种非常简单的方法是创建UINavigationController类的扩展。

因为重写preferredStatusBarStyle:方法不会工作,除非我们在UINavigationController类内部做它。

    extension UINavigationController {
        open override var preferredStatusBarStyle: UIStatusBarStyle {
            return .lightContent
        }
    }