状态栏背景颜色不会更改为自定义颜色

时间:2018-01-15 10:54:43

标签: ios swift colors statusbar uistatusbar

当我将状态栏背景颜色更改为原生UIColor.gray时,它会发生变化。 但是,当我想使用自定义颜色时,它会变成黑色。

UIApplication.shared.statusBarView?.backgroundColor = UIColor.gray - 此代码工作正常。状态栏背景颜色为灰色

UIApplication.shared.statusBarView?.backgroundColor = UIColor(red: 30/255, green: 30/255, blue: 30/255, alpha: 1) - 此代码工作不正确。状态栏背景颜色为黑色

3 个答案:

答案 0 :(得分:4)

首先,在info.plist文件中设置基于视图控制器的状态栏外观属性。

然后在AppDelegate Class的didFinishLaunchingWithOptions方法中添加以下代码。

if let status = UIApplication.shared.value(forKey: "statusBar") as? UIView {
        status.backgroundColor = UIColor.init(red: 173.0/255.0, green: 173.0/255.0, blue: 44.0/255.0, alpha: 1)
     }

UIApplication.shared.statusBarStyle = .lightContent

希望这会对你有所帮助。

答案 1 :(得分:3)

这可以帮助你在Swift 4.看起来像一个hacky技巧,但有效。

您可以在应用程序启动期间或视图控制器的viewDidLoad期间为状态栏设置背景颜色。

extension UIApplication {

    var statusBarView: UIView? {
        return value(forKey: "statusBar") as? UIView
    }

}

// Set upon application launch, if you've application based status bar
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        UIApplication.shared.statusBarView?.backgroundColor = UIColor.red
        return true
    }
}


or 
// Set it from your view controller if you've view controller based statusbar
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        UIApplication.shared.statusBarView?.backgroundColor = UIColor.red
    }

}



结果如下:

enter image description here

答案 2 :(得分:1)

代码不正确,只是您提供的颜色本身是dark gray(R:30,G:30,B:30)代表dark gray,即status bar中使用的内容,将此颜色更改为其他颜色,例如(R:202,G:0,B:42),它将显示red颜色

尝试

UIApplication.shared.statusBarView?.backgroundColor = UIColor(red: 202/255, green: 0/255, blue: 42/255, alpha: 1)

相关问题