【问题标题】:UIApplication.shared.keyWindow?.addSubview not workingUIApplication.shared.keyWindow?.addSubview 不工作
【发布时间】:2020-03-21 11:59:25
【问题描述】:

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")
           }
    }

这是此问题的屏幕截图。

【问题讨论】:

    标签: ios13 xcode11 swift5 ios13.2


    【解决方案1】:

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

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

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

    但是,当您从didFinishLaunchingWithOptions 调用 addSubview() 时,viewControllers 将被添加到它上面,因此它可能不可见(至少对我来说是这样,在使用导航控制器时)。

    要对此进行测试,请在运行应用程序时单击 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
        }
    }
    

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

    【讨论】:

      猜你喜欢
      • 2012-10-12
      • 1970-01-01
      • 2013-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多