How to set Status Bar Style in Swift 3

2019-01-05 07:43发布

I'm using Xcode 8.0 beta 4.

In previous version, UIViewController have method to set the status bar style

public func preferredStatusBarStyle() -> UIStatusBarStyle

However, I found it changed to a "Get ONLY varaiable" in Swift 3.

public var preferredStatusBarStyle: UIStatusBarStyle { get } 

How can provide the style to use in my UIViewController?

28条回答
太酷不给撩
2楼-- · 2019-01-05 08:08

You could try to override the value returned, rather than setting it. The method is declared as { get }, so just provide a getter:

 override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
}

If you set this conditionally, you'll need to call setNeedsStatusBarAppearanceUpdate() so it'll animate the change when you're ready

查看更多
Ridiculous、
3楼-- · 2019-01-05 08:08
override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
}

This worked for me :) I have Navigation Controller embedded in my view controllers with navigation bar hidden. I wanted to set status bar light on some of the viewsin app.

查看更多
走好不送
4楼-- · 2019-01-05 08:10

iOS 11.2

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    UINavigationBar.appearance().barStyle = .black

    return true
}
查看更多
Lonely孤独者°
5楼-- · 2019-01-05 08:10

I was getting:

Overriding var must be as accessible as its enclosing type

Which is fixed by adding public like:

override public var preferredStatusBarStyle: UIStatusBarStyle {
    get {
        return .lightContent
    }
}

On Swift3 iOS10.

查看更多
贼婆χ
6楼-- · 2019-01-05 08:11

Swift 4+

for white statusbar text:

navigationController.navigationBar.barStyle = .blackTranslucent
查看更多
戒情不戒烟
7楼-- · 2019-01-05 08:11

To add to the great asnwer by @Krunal https://stackoverflow.com/a/49552326/4697535

In case you are using a UINavigationController, the preferredStatusBarStyle will have no effect on the UIViewController.

Xcode 10 and Swift 4.

Set a custom UINavigationController

Example:

class LightNavigationController: UINavigationController {

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

Use an extension for an app level solution:

extension UINavigationController {

  open override var preferredStatusBarStyle: UIStatusBarStyle {
      guard let index = tabBarController?.selectedIndex else { return .default }
      switch index {
      case 0, 1, 2: return .lightContent // set lightContent for tabs 0-2
      default: return .default // set dark for tab 3
      }
  }
}
查看更多
登录 后发表回答