Created
January 7, 2015 23:31
-
-
Save originell/a42b2b83c2ca1865ed20 to your computer and use it in GitHub Desktop.
Reliably get the top most UIViewController. Tested with iOS7 and 8
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Note: There are no fancy error checks in here. This is just meant to quickly demonstrate this. | |
// I was extremely frustrated because most posts on stackoverflow are missing the important point | |
// of checking for the "presentedViewController". | |
// If you are working in a view that is *already living* in the view hierarchy. | |
var topMostController = view.window!.rootViewController! | |
// or | |
// If you don't have a view in the hierarchy yet (as it might happen in viewDidLoad etc.) | |
// (there is also the possibility to use UIApplication.sharedApplication().keyWindow, though it seems | |
// that the internet's general opinion is that it's safer to use the delegate's window) | |
var topMostController = UIApplication().sharedApplication().delegate!.window!!.rootViewController | |
// Important: do not forgot to check for this. Presented ViewControllers are in front of others! | |
// TODO: Might be necessary to do this recursively? | |
if let presentedVC = topMostController.presentedViewController { | |
topMostController = presentedVC | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment