1. 程式人生 > >改變狀態列(StatusBar)的顏色

改變狀態列(StatusBar)的顏色

全域性修改狀態列的顏色

預設的情況下statusBar的顏色顯示為黑色,如果我們想改為白色,那麼可以如下操作:

1)開啟專案的plist檔案,設定View controller-based status bar appearance" 為 NO


2 在AppDelegate.swift檔案中的啟動方法中設定UIApplication.shared.statusBarStyle = .lightContent

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        let nav = UINavigationBar.appearance()
        nav.barTintColor = UIColor.red
        UIApplication.shared.statusBarStyle = .lightContent
        
        return true
    }
再次執行程式,我們就可以看到statusBar由黑色變為白色了,下面是幾張效果圖,依次是修改之前,修改之後:

  

但是以上操作會修改所有介面的statusBar顏色,如果我只需要具體頁面statusBar為白色,那麼可以進行如下操作。

設定具體頁面的statusBar顏色為白色

1)去除AppDelegate.swift檔案中的啟動方法中設定UIApplication.shared.statusBarStyle = .lightContent

2)在具體頁面的viewWillAppear和viewWillDisappear中進行設定,這裡我在SecondViewController中進行設定,對比

ViewController的顯示效果

class SecondViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title = "Second"
        view.backgroundColor = UIColor.white
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        UIApplication.shared.statusBarStyle = .lightContent
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        UIApplication.shared.statusBarStyle = .default
    }
}
效果如下:

 

設定狀態列背景顏色

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        let statusBar: UIView = UIApplication.shared.value(forKey: "statusBar") as! UIView
        if statusBar.responds(to: #selector(setter: UIView.backgroundColor)) {
            statusBar.backgroundColor = UIColor.yellow
        }
        return true
    }


可以為UIApplication擴充套件一個類屬性,方便使用

extension UIApplication {
    class var statusBarBackgroundColor: UIColor? {
        get {
            return (shared.value(forKey: "statusBar") as? UIView)?.backgroundColor
        } set {
            (shared.value(forKey: "statusBar") as? UIView)?.backgroundColor = newValue
        }
    }
}