Swift - 更改缺口设备上的状态栏颜色

问题描述

我知道这个问题已经被问到并得到了很多回答,但我似乎无法让它发挥作用。

我有一个带有全尺寸 WKWebView 的 UIViewController。一切正常,除了在缺口设备上看起来不合适的状态栏。 问题是,没有任何效果,即使是我自己的其他应用程序代码

到目前为止我尝试过的事情(这在另一个应用程序中工作得很好......):

if #available(iOS 13,*)
        {
            let statusBar = UIView(frame: (UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.windowScene?.statusBarManager?.statusBarFrame)!)
            //statusBar.backgroundColor = UIColor(red: 242/255,green: 242/255,blue: 242/255,alpha: 1.0)
            statusBar.backgroundColor = UIColor.red
            UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.addSubview(statusBar)
        }
        else
        {
            let statusBar: UIView = UIApplication.shared.value(forKey: "statusBar") as! UIView
            
            if statusBar.responds(to:#selector(setter: UIView.backgroundColor))
            {
                statusBar.backgroundColor = UIColor(red: 242/255,alpha: 1.0)
            }
        } 

还有这个:

extension UIApplication {

    var statusBarUIView: UIView? {

        if #available(iOS 13.0,*) {
            let tag = 3848245

            let keyWindow: UIWindow? = UIApplication.shared.windows.filter {$0.isKeyWindow}.first

            if let statusBar = keyWindow?.viewWithTag(tag) {
                return statusBar
            } else {
                let height = keyWindow?.windowScene?.statusBarManager?.statusBarFrame ?? .zero
                let statusBarView = UIView(frame: height)
                statusBarView.tag = tag
                statusBarView.layer.zPosition = 999999

                keyWindow?.addSubview(statusBarView)
                return statusBarView
            }

        } else {

            if responds(to: Selector(("statusBar"))) {
                return value(forKey: "statusBar") as? UIView
            }
        }
        return nil
      }
}

还有这里的一切:

How to change the status bar background color and text color on iOS 13?

Change Status Bar Color in iOS 13?

How to set Status Bar Style in Swift 3

甚至尝试从显示在 WKWebView 中的网页上执行此操作: https://itnext.io/make-your-pwas-look-handsome-on-ios-fd8fdfcd5777

解决问题的唯一解决方法是更改​​主视图的背景颜色。 问题是,这也会改变底部的颜色。

我什至尝试弄乱 info.plist 文件中的样式。

对我缺少的东西有什么想法吗?

解决方法

你可以把它添加到你的控制器中,然后你检查 hasNotch

extension UIDevice {
    /// Returns `true` if the device has a notch
    var hasNotch: Bool {
        guard #available(iOS 11.0,*),let window = UIApplication.shared.windows.first(where: { $0.isKeyWindow }),window.safeAreaInsets.bottom >= 10 else {
            return false
        }
        
        return true
    }
}