为整个屏幕添加黑色覆盖,包括状态栏

Add black overlay to entire screen including status bar

我有一个带有 UINavigationControllerUITabBarController 的应用程序。 UITabBarController 内部是一个应该呈现模态视图的按钮,为此我想用褪色的背景(黑色和 .5 alpha)将整个屏幕涂黑。

我按如下方式使用 UIView() 执行此操作,这是在 UITabBarController class:

中设置的
let fadeBackground: UIView = {
    let fadeBackground = UIView(frame: self.view.frame)
    fadeBackground.backgroundColor = UIColor.black
    fadeBackground.alpha = 0.5
    return fadeBackground
}()

然后我用 view.addSubview(fadeBackground) 将它添加到我的视图中。然而,这 returns 褪色的背景高于一切,包括 UINavigationControllerUITabBarController,但它不覆盖状态栏。为了显示:

我现在想知道如何将我创建的 UIView() 添加到顶部位置,使其也越过状态栏。我知道这可能很棘手,但我见过状态栏上方有黑条的应用程序,所以我认为这就是我需要的,然后相应地将 alpha 设置为 .5。

到目前为止我尝试了什么:

但似乎都不起作用。我也尝试将 UIView() 添加到带有 UIApplication.shared.keyWindow?.addSubview(fadeBackground) 的 keyWindow,但也没有成功。有什么想法或建议吗?

试试这个,它会在整个屏幕上添加一个视图,包括状态栏,

if let appDelegate = UIApplication.shared.delegate as? AppDelegate, let window = appDelegate.window {
        let windowFrame = window.frame
        let overlayView = UIView(frame: windowFrame)
        imageView.backgroundColor = UIColor.black.withAlphaComponent(0.7)
        window.addSubview(overlayView)
    }

您可以在 StatusBarView 中添加另一个子视图,使里面的文本也淡化。

extension UIApplication {
    var statusBarView: UIView? {
        return value(forKey: "statusBar") as? UIView
    }
}

然后在ViewController:

class CustomTabBarController: UITabBarController {
    lazy var fadeStatusBarBackground: UIView = {
        let fadeBackground = UIView(frame: UIApplication.shared.statusBarView?.frame ?? .zero)
        fadeBackground.backgroundColor = UIColor.black
        fadeBackground.alpha = 0.5
        return fadeBackground
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        UIApplication.shared.statusBarView?.addSubview(fadeStatusBarBackground)
    }
}