Reputation: 192
I have an overlay (UIImageView)
which should have a transparent background and alpha. How can I set the imageview
such that it covers the entire screen? Currently, it covers the screen but not the UIStatusBar
. I am adding the view in AppDelegate's
main window
as a subview
.
The code:
let overlay1 = UIImageView(image: UIImage(named: "overlay-image"))
overlay1.contentMode = .scaleAspectFit
overlay1.backgroundColor = UIColor.black
overlay1.alpha = 0.87
overlay1.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
overlay1.isUserInteractionEnabled = true
overlay1.layer.zPosition = 1
(UIApplication.shared.delegate as? AppDelegate).window.addSubview(overlay1)
Upvotes: 1
Views: 3529
Reputation: 13354
After discussion in comments found that changing the backgroundColor
of statusBar
is the reason why your code is not working properly.
By printing the superView
of statusBar
I found that statusBar
is not added on UIWindow
instead it is on UIStatusBarWindow
which is probably above the mainWindow
.
Also please don't use force unwrapping it can be cause of crash. At last I put a guard
to fetch the statusBar
, to check if it responds to backgroundColor
property, to fetch its superView
and adding the overlay on this superView
got it working.
Your check for respondToSelector
is also wrong. See below code it works as per your requirement.
guard let statusBar = UIApplication.shared.value(forKey: "statusBar") as? UIView, statusBar.responds(to: NSSelectorFromString("backgroundColor")), let superView = statusBar.superview else {return}
statusBar.backgroundColor = UIColor.red
let overlay1 = UIImageView(image: UIImage(named: "overlay-image"))
overlay1.contentMode = .scaleAspectFit
overlay1.backgroundColor = UIColor.black
overlay1.alpha = 0.87
overlay1.frame = superView.bounds
overlay1.isUserInteractionEnabled = true
overlay1.layer.zPosition = 1
superView.addSubview(overlay1)
Note: Changing the statusBar
color is not recommended. You can set its style to default
or light
.
Upvotes: 1
Reputation: 7605
Okay I just tried with something and it worked. Just use it in your ViewController
like:
// You should be using viewDidAppear(_:)
override func viewDidAppear(_ animated: Bool) {
if let appDelegate = UIApplication.shared.delegate as? AppDelegate, let window = appDelegate.window {
let windowFrame = window.frame
let imageView = UIImageView(frame: windowFrame)
imageView.image = #imageLiteral(resourceName: "TakeOff") // use your image
imageView.contentMode = .scaleAspectFit
imageView.backgroundColor = UIColor.green.withAlphaComponent(0.2) // replace green with the color you want
window.addSubview(imageView)
}
}
But, remember one thing. It's not a good idea to add an image view as an overlay. You should always use a
UIView
as an overlay and add the image view as a sub view to that overlay.
Upvotes: 0