单纯的设置状态栏颜色:
func setStatusBarBackgroundColor(color:UIColor) {
if #available(iOS 13.0, *) {
let tag = 987654321
let keyWindow = UIApplication.shared.connectedScenes.map({ $0 as? UIWindowScene }).compactMap({ $0 }).first?.windows.first
if let statusBar = keyWindow?.viewWithTag(tag) {
statusBar.backgroundColor = color
} else {
let statusBar = UIView(frame:keyWindow?.windowScene?.statusBarManager?.statusBarFrame ?? CGRect.zero)
if statusBar.responds(to:#selector(setter: UIView.backgroundColor)) {
statusBar.backgroundColor = color
}
statusBar.tag = tag
keyWindow?.addSubview(statusBar)
}
} else {
let statusBar: UIView = UIApplication.shared.value(forKey: "statusBar") as! UIView
if statusBar.responds(to:#selector(setter: UIView.backgroundColor)) {
statusBar.backgroundColor = color
}
}
}
如果有获取状态栏背景颜色的需求可以用下面这种方式:
extension UIApplication {
class var statusBarBackgroundColor: UIColor? {
get {
if #available(iOS 13.0, *) {
let tag = 987654321
let keyWindow = UIApplication.shared.connectedScenes.map({ $0 as? UIWindowScene }).compactMap({ $0 }).first?.windows.first
if let statusBar = keyWindow?.viewWithTag(tag) {
return statusBar.backgroundColor
}
let statusBar = UIView(frame: 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
let keyWindow = UIApplication.shared.connectedScenes.map({ $0 as? UIWindowScene }).compactMap({ $0 }).first?.windows.first
if let statusBar = keyWindow?.viewWithTag(tag) {
statusBar.backgroundColor = newValue
} else {
let statusBar = UIView(frame:keyWindow?.windowScene?.statusBarManager?.statusBarFrame ?? CGRect.zero)
if statusBar.responds(to:#selector(setter: UIView.backgroundColor)) {
statusBar.backgroundColor = newValue
}
statusBar.tag = tag
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
}
}
}
}
}
还可以通过加一个view的方式来改变:
func setStatusBarBackgroundColor(_ color: UIColor?) {
guard let color = color else {
return
}
let statusBarView = UIView()
statusBarView.backgroundColor = color
self.view.addSubview(statusBarView)
statusBarView.translatesAutoresizingMaskIntoConstraints = false
statusBarView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
statusBarView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
statusBarView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
statusBarView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor).isActive = true
}