Swift 5:状态栏颜色管理与方向变化

Swift 5: Status Bar Color Management with Orientation Changes

IOS15,Xcode13.2.1,Swift5

我希望在我的多视图控制器应用程序中管理状态栏颜色。我已成功找到如何更改每个控制器和纵向状态栏的颜色。问题是当转向横向时,状态栏消失,纵向模式下状态栏大小的矩形覆盖导航区域的左侧。

这是我的代码和用法:

func statusBarColor() {
    if #available(iOS 13.0, *) {
        
        let statusBar2 =  UIView()
        if UIApplication.shared.currentScene?.statusBarManager!.statusBarFrame != nil {
            statusBar2.frame = (UIApplication.shared.currentScene?.statusBarManager!.statusBarFrame)!
            statusBar2.backgroundColor = UIColor.init(named: "BackGroundColor")
            UIApplication.shared.windows.first?.addSubview(statusBar2)
        }
    } else {
        let statusBar2: UIView = UIApplication.shared.value(forKey: "statusBar") as! UIView
        statusBar2.backgroundColor = UIColor.init(named: "BackGroundColor")
    }
}

使用:调用viewWillAppear中的函数

问题图片:status bar in landscape mode (Navigation bar covered)

感谢马特在问题评论中的提示,我找到了一个可行的答案。应该注意的是,由于不相关的错误,这在我的应用程序中可能是必需的,这可以被视为补丁,而不是错误的解决方案。此代码创建一个具有背景色的视图并将其放置在状态栏中。当设备处于横向模式和离开当前 viewController.

时,视图将被隐藏

这适用于 Swift 5、iOS 15、Xcode 13.2.1

class TableViewController: UITableViewController {

    let statusBar1 = UIView()
    
    override func viewWillAppear(_ animated: Bool) {
        statusBarColor()
        statusBar1.isHidden = false
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        statusBar1.isHidden = true
    }
    
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        if UIDevice.current.orientation.isLandscape {
            statusBar1.isHidden = true
        } else {
            statusBar1.isHidden = false
        }
    }

    func statusBarColor() {
        if #available(iOS 13.0, *) {

            self.statusBar1.frame = (UIApplication.shared.currentScene?.statusBarManager!.statusBarFrame)!
            self.statusBar1.backgroundColor = UIColor.init(named: "AccentColor")

            UIApplication.shared.windows.first?.addSubview(statusBar1)

        } else {

           let statusBar2: UIView = UIApplication.shared.value(forKey: "statusBar") as! UIView
           statusBar2.backgroundColor = UIColor.init(named: "AccentColor")
        }
    }
}