2

UIApplication.shared.keyWindow?.addSubview 在 ios13 中不起作用

我尝试了很多选择,但没有找到任何解决方案。我希望每个屏幕状态栏都以 AppDelegate 的形式呈现蓝色。

我试试这段代码。

if #available(iOS 13.0, *) {
         /*  let window = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
           // Reference - https://stackoverflow.com/a/57899013/7316675
           let statusBar = UIView(frame: window?.windowScene?.statusBarManager?.statusBarFrame ?? CGRect.zero)
           statusBar.backgroundColor = publicMethod().hexStringToUIColor(hex: "#033d6f")
           window?.addSubview(statusBar)
         */
        let statusBar =  UIView()
        statusBar.frame = UIApplication.shared.statusBarFrame
        statusBar.backgroundColor = .blue
        UIApplication.shared.statusBarStyle = .lightContent
        UIApplication.shared.keyWindow?.addSubview(statusBar)

    } else {
          let statusBar: UIView = UIApplication.shared.value(forKey: "statusBar") as! UIView
           if statusBar.responds(to:#selector(setter: UIView.backgroundColor)) {
               //statusBar.backgroundColor = UIColor.darkGray
               statusBar.backgroundColor = publicMethod().hexStringToUIColor(hex: "#033d6f")
           }
    }

这是此问题的屏幕截图。 在此处输入图像描述

4

1 回答 1

0

您现在可能已经解决了这个问题,但是以防万一其他人将来偶然发现它,我会用我正在工作的代码来回答它。

首先,由于您想从 AppDelegate 运行这段代码,我假设您是从didFinishLaunchingWithOptions.

在这种情况下,请确保在调用之前不要运行代码,makeKeyAndVisible()否则 keyWindow 将为 nil。

但是,当您从 viewControllers 调用addSubview ()didFinishLaunchingWithOptions时,viewControllers 将被添加到它之上,因此它可能不可见(至少在我使用 navigationController 时是这样)。

要对此进行测试,请在运行应用程序时单击 xCode 中的Debug View Hierarchy按钮,如图所示。

在此处输入图像描述

您可以拖动屏幕从不同角度查看视图层次结构,如下图所示:

在此处输入图像描述

如果是这种情况,您可以通过设置 zPosition 使 statusBar 成为最顶层视图:statusBar.layer.zPosition = .greatestFiniteMagnitude

所以我的完整代码是:

func setStatusBar() {
    if #available(iOS 13.0, *) {
        let statusBar = UIView(frame: UIApplication.shared.keyWindow?.windowScene?.statusBarManager?.statusBarFrame ?? CGRect.zero)
        statusBar.backgroundColor = .blue
        UIApplication.shared.keyWindow?.addSubview(statusBar)
        statusBar.layer.zPosition = .greatestFiniteMagnitude
    } else {
        let statusbar = UIApplication.shared.value(forKey: "statusBar") as? UIView
        statusbar?.backgroundColor = .blue
    }
}

同样,如果之前调用此函数,这将在 iOS 13 中不起作用makeKeyAndVisible()

于 2020-04-27T10:04:13.290 回答