單純的設(shè)置狀態(tài)欄顏色:
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
}
}
}
如果有獲取狀態(tài)欄背景顏色的需求可以用下面這種方式:
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
}