首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >UIApplication.shared.keyWindow?.addSubview不工作

UIApplication.shared.keyWindow?.addSubview不工作
EN

Stack Overflow用户
提问于 2019-11-26 13:57:27
回答 1查看 401关注 0票数 2

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

我尝试了许多选择,但没有找到任何解决方案。我要每个屏幕的状态栏使蓝色的形式AppDelegate。

我尝试了这个代码。

代码语言:javascript
复制
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")
           }
    }

这是这个问题的截图。

EN

回答 1

Stack Overflow用户

发布于 2020-04-27 18:04:13

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

首先,因为您想要从AppDelegate运行这段代码,所以我假设您是从didFinishLaunchingWithOptions运行它。

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

但是,当您从didFinishLaunchingWithOptions调用addSubview()时,viewControllers将被添加到它的顶部,因此它可能是不可见的(至少对于我来说,在使用navigationController时是这样)。

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

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

如果是这种情况,您可以通过设置zPosition:statusBar.layer.zPosition = .greatestFiniteMagnitude将statusBar设置为最上面的视图

所以我的完整代码是:

代码语言:javascript
复制
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中将不起作用

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59044619

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档