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

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


当前回答

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

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 3

.plist

View controller-based status bar appearance = NO

AppDelegate.swift

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Custom statubar
        UIApplication.shared.isStatusBarHidden = false
        UIApplication.shared.statusBarStyle = .lightContent
        let statusBar: UIView = UIApplication.shared.value(forKey: "statusBar") as! UIView
        statusBar.backgroundColor = UIColor.gray

        return true
    }

适用于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)

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

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

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

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

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

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

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

Objective - C

[self setNeedsStatusBarAppearanceUpdate];

-(UIStatusBarStyle)preferredStatusBarStyle {
     return UIStatusBarStyleLightContent;
}

斯威夫特

setNeedsStatusBarAppearanceUpdate()

var preferredStatusBarStyle: UIStatusBarStyle { 
    return .lightContent
}

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