Use autolayout on view added to UIWindow

If you need to draw on the entire window, here is code to do it (in this example I am in the AppDelegate, so window is the AppDelegate.window property).

func tryToDrawOnTheWindow()
{
    if let window = window, view = window.rootViewController?.view
    {
            print("I have a root view")

            let infoSc = InfoScreenView(frame: view.frame)
            let count = view.subviews.count
            view.insertSubview(infoSc, atIndex: count)
            infoSc.translatesAutoresizingMaskIntoConstraints = false
            let height = NSLayoutConstraint(item: infoSc, attribute: .Height, relatedBy: .Equal, toItem: view, attribute: .Height, multiplier: 1, constant: 0)
            let width = NSLayoutConstraint(item: infoSc, attribute: .Width, relatedBy: .Equal, toItem: view, attribute: .Width, multiplier: 1, constant: 0)
            let offset = NSLayoutConstraint(item: infoSc, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 0)
            print([height, width, offset])
            view.addConstraints([height, width, offset])
    }
    else
    {
        print("No root view on which to draw")
    }
}

This will let you draw on top of whatever is in the view hierarchy. In my test app, I added a textfield and a blue rect, and the overlay was orange with 40% opacity. Bear in mind that by default the overlay view will consume all taps in this case.

Tags:

Ios

Swift