PennyWise
PennyWise

Reputation: 647

Add black overlay to entire screen including status bar

I have an application with a UINavigationController and a UITabBarController. Inside the UITabBarController is a button which should present a modal view, for which I want to black out the entire screen with a faded background (black with .5 alpha).

I do this with a UIView() as follows, this is set inside the UITabBarController class:

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

I then add it to my view with view.addSubview(fadeBackground). This, however, returns the faded background above everything, including the UINavigationController and UITabBarController, but it does not overlay the status bar. To illustrate: entire screen is faded, except status bar

I am now wondering how I can add the UIView() I created to the top position, so it goes over the status bar as well. I know it might be tricky, but I have seen applications where there is a black bar over the status bar, so I think this is what I need and then set the alpha to .5 accordingly.

What have I tried so far:

But neither seem to work. I have also tried adding the UIView() to the keyWindow with UIApplication.shared.keyWindow?.addSubview(fadeBackground), but also without success. Any ideas or suggestions?

Upvotes: 0

Views: 1277

Answers (2)

Mateusz Tylman
Mateusz Tylman

Reputation: 271

You can add another subview just inside StatusBarView to make text inside also faded.

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

And then in 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)
    }
}

Upvotes: 2

Sumeet.Jain
Sumeet.Jain

Reputation: 1609

Try this, it will add an view over the entire screen including statusBar,

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

Upvotes: 0

Related Questions