0

I would like to put a UIView above all other views. I saw that this is possible using the UIScreen object. However, it looks like the UIScreen doesn't have a Safe Area. This let's the View overlap with the Statusbar.

How can I place a View above all other Views while still using the Safe Area Insets?

I'm using this code in the Appdelegate's DidFinishLaunchingWithOptions():

window?.makeKeyAndVisible()

let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = UIColor.red
window?.addSubview(view)
window?.bringSubview(toFront: view)

let heightConstraint = NSLayoutConstraint(item: view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 44)
view.addConstraint(heightConstraint)

let layoutGuide = window!.safeAreaLayoutGuide
let layoutGuideConstraints = [
    view.topAnchor.constraint(equalTo: layoutGuide.topAnchor, constant: 8),
    view.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor, constant: 8),
    view.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor, constant: -8)
]
NSLayoutConstraint.activate(layoutGuideConstraints)

Example of the executed code.

evenwerk
  • 947
  • 1
  • 12
  • 28
  • 2
    Safe area guide is unfortunately another epic fail overall. In your case I would personally try avoiding adding anything on window directly and find another solution to what you are doing. There is a way of having a single view controller on the bottom which controls the whole app hierarchy internally on its view. That controller may then have another view designed for your overlay. But in your case you just might have a shot if you instead of add this detached view create a new view controller and add that as a child view controller to your window... – Matic Oblak Mar 01 '18 at 11:25
  • @MaticOblak I think you are right, this might be the most reliable solution. – evenwerk Mar 01 '18 at 11:28
  • 1
    Have a look to this class / lib. I think it does what you need: https://github.com/Daltron/NotificationBanner/blob/master/NotificationBanner/Classes/BaseNotificationBanner.swift – Xavier Bauquet Mar 01 '18 at 12:59

0 Answers0