改变状态栏(StatusBar)的颜色

来源:互联网 发布:淘宝怎么升级心 编辑:程序博客网 时间:2024/05/16 17:23
全局修改状态栏的颜色

默认的情况下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        }    }}




原创粉丝点击