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

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


当前回答

适用于基于导航的应用

    var addStatusBar = UIView()
    addStatusBar.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 20);
    addStatusBar.backgroundColor = global().UIColorFromRGB(0x65b4d9)
    self.window?.rootViewController?.view .addSubview(addStatusBar)

其他回答

适用于基于导航的应用

    var addStatusBar = UIView()
    addStatusBar.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 20);
    addStatusBar.backgroundColor = global().UIColorFromRGB(0x65b4d9)
    self.window?.rootViewController?.view .addSubview(addStatusBar)

Swift 4.2解决方案与NavigationController

第一步:

打开你的信息。并插入一个名为“View controller based status bar appearance”或UIViewControllerBasedStatusBarAppearance的新键到YES,让每个VC使用自己的状态属性。

第二步

在每个VC中,像这样重写preferredStatusBarStyle属性:

override var preferredStatusBarStyle : UIStatusBarStyle {
    return .lightContent //.default for black style
}

最后一步

重写自定义NavigationController类中的preferredStatusBarStyle属性:

class NavigationController : UINavigationController {

override var preferredStatusBarStyle : UIStatusBarStyle {

    if let topVC = viewControllers.last {
        //return the status property of each VC, look at step 2
        return topVC.preferredStatusBarStyle  
    }

    return .default
}

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

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

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

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

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

Objective - C

[self setNeedsStatusBarAppearanceUpdate];

-(UIStatusBarStyle)preferredStatusBarStyle {
     return UIStatusBarStyleLightContent;
}

斯威夫特

setNeedsStatusBarAppearanceUpdate()

var preferredStatusBarStyle: UIStatusBarStyle { 
    return .lightContent
}

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

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

override func viewWillAppear(animated: Bool) {
    self.navigationController?.navigationBarHidden =  true

    UIApplication.sharedApplication().statusBarHidden = false
    UIApplication.sharedApplication().statusBarStyle = .LightContent

    let statusBar: UIView = UIApplication.sharedApplication().valueForKey("statusBar") as! UIView
    if statusBar.respondsToSelector("setBackgroundColor:") {
        statusBar.backgroundColor = UIColor.redColor()
    }

}