小编典典

在Swift 3中更改状态栏背景颜色

swift

在XCode 7.3.x中,我用以下方法更改了StatusBar的背景颜色:

func setStatusBarBackgroundColor(color: UIColor) {
guard  let statusBar = UIApplication.sharedApplication().valueForKey("statusBarWindow")?.valueForKey("statusBar") as? UIView else {
    return
}
statusBar.backgroundColor = color
}

但是似乎这在Swift 3.0中不再起作用。

病态尝试:

func setStatusBarBackgroundColor(color: UIColor) {
guard  let statusBar = (UIApplication.shared.value(forKey: "statusBarWindow") as AnyObject).value(forKey: "statusBar") as? UIView else {
    return
}
statusBar.backgroundColor = color
}

但这给了我:

this class is not key value coding-compliant for the key statusBar.

有任何想法如何使用XCode8 / Swift 3.0进行更改吗?


阅读 700

收藏
2020-07-07

共1个答案

小编典典

extension UIApplication {
var statusBarView: UIView? {
if responds(to: Selector((“statusBar”))) {
return value(forKey: “statusBar”) as? UIView
}
return nil
}
}

UIApplication.shared.statusBarView?.backgroundColor = .red

iOS 13更新

在UIApplication上名为-statusBar或-
statusBarWindow的应用程序:必须更改此代码,因为不再有状态栏或状态栏窗口。而是在窗口场景上使用statusBarManager对象。

2020-07-07