swift修改状态栏背景颜色与字体颜色

状态栏中可设置的颜色有背景颜色和字体颜色
修改状态栏中背景颜色:

extension UIApplication {
class var statusBarBackgroundColor: UIColor? {
 get {
        if #available(iOS 13.0, *) {
          let tag = 987654321

          if let statusBar = UIApplication.shared.keyWindow?.viewWithTag(tag) {
                    return statusBar.backgroundColor
                }
                    let statusBar = UIView(frame: UIApplication.shared.keyWindow?.windowScene?.statusBarManager?.statusBarFrame ?? CGRect.zero)
            return statusBar.backgroundColor
                } else {
                    let statusBar: UIView = UIApplication.shared.value(forKey: "statusBar") as! UIView
                    return statusBar.backgroundColor
                }
    }
    set {
        if #available(iOS 13.0, *) {
            let tag = 987654321

            if let statusBar = UIApplication.shared.keyWindow?.viewWithTag(tag) {
                statusBar.backgroundColor = newValue
            } else {
                let statusBar = UIView(frame: UIApplication.shared.keyWindow?.windowScene?.statusBarManager?.statusBarFrame ?? CGRect.zero)
                if statusBar.responds(to:#selector(setter: UIView.backgroundColor)) {
                    statusBar.backgroundColor = newValue
                }
                statusBar.tag = tag
                UIApplication.shared.keyWindow?.addSubview(statusBar)
            }
        } else {
                    let statusBar: UIView = UIApplication.shared.value(forKey: "statusBar") as! UIView
                    if statusBar.responds(to:#selector(setter: UIView.backgroundColor)) {
                        statusBar.backgroundColor = newValue
                    }
                }
    }
}
}

修改状态栏字体颜色

 var style: UIStatusBarStyle = .default
 
 override var preferredStatusBarStyle: UIStatusBarStyle {        return self.style
 }

//设置字体颜色并刷新状态栏
self.style = .lightContent
            
setNeedsStatusBarAppearanceUpdate()

你可能感兴趣的:(Swift,ios)