改变状态栏(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
        }
    }
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值