Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add view in top of view hierarchy in Swift?

I have been using this:

UIApplication.sharedApplication().keyWindow?.rootViewController!.view.addSubview(self.customView)

To add a modal view over all the views in the view hierarchy in app.

But this is giving me problem. It adds subview as expected sometimes but sometimes it doesn't' work. In what case this wont work and what's the best way to add modal view in view hierarchy like UIAlertView.

like image 840
Prajeet Shrestha Avatar asked May 08 '16 08:05

Prajeet Shrestha


1 Answers

Depending on what's happening, there can be more than one UIWindow at a time - for example, if a system alert shows up, you will have two separate windows (one for your view controller, one for the alert itself).
A similar example can be made for the system keyboard. If the keyboard has focus, that will be your keyWindow.

A way of making sure you are adding the subview on top of all windows, could be: UIApplication.sharedApplication().windows.last?.addSubview(yourSubView).

I've also seen people using the application delegate, with: UIApplication.sharedApplication().delegate?.window.

like image 134
Smnd Avatar answered Nov 09 '22 23:11

Smnd