3

早些时候在 Xcode 10 和 swift 5 上,我曾经如下更改状态栏颜色:-

if let statusBar = UIApplication.shared.value(forKey: "statusBar") as? UIView {
   if statusBar.responds(to: #selector(setter: UIView.backgroundColor)) {
      statusBar.backgroundColor = #colorLiteral(red: 0, green: 0.7156304717, blue: 0.9302947521, alpha: 1)
   }
}

现在在 Xcode 11 和 Swift 5.1 上出现以下错误:-

由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“在 UIApplication 上调用 -statusBar 或 -statusBarWindow 的应用程序:必须更改此代码,因为不再有状态栏或状态栏窗口。在窗口场景中使用 statusBarManager 对象。

有什么建议么?

4

1 回答 1

5

尝试这个:

extension UIApplication {


class var statusBarBackgroundColor: UIColor? {
    get {
        return statusBarUIView?.backgroundColor
    } set {
        statusBarUIView?.backgroundColor = newValue
    }
}

class var statusBarUIView: UIView? {
    if #available(iOS 13.0, *) {
        let tag = 987654321

        if let statusBar = UIApplication.shared.keyWindow?.viewWithTag(tag) {
            return statusBar
        }
        else {
            let statusBarView = UIView(frame: UIApplication.shared.statusBarFrame)
            statusBarView.tag = tag

            UIApplication.shared.keyWindow?.addSubview(statusBarView)
            return statusBarView
        }
    } else {
        if responds(to: Selector(("statusBar"))) {
            return value(forKey: "statusBar") as? UIView
        }
    }
    return nil
}}
于 2019-09-17T13:22:32.200 回答