I've run into a couple of cases now where it would be convenient to be able to find the "topmost" view controller (the one responsible for the current view), but haven't found a way to do it.
Basically the challenge is this: Given that one is executing in a class that is not a view controller (or a view) [and does not have the address of an active view] and has not been passed the address of the topmost view controller (or, say, the address of the navigation controller), is it possible to find that view controller? (And, if so, how?)
Or, failing that, is it possible to find the topmost view?
This works great for finding the top viewController 1 from any root view controlle
I think you need a combination of the accepted answer and @fishstix's
Swift 3.0+
Swift:
Usage:
Getting top most view controller for Swift using extensions
Code:
Usage:
To complete Eric's answer (who left out popovers, navigation controllers, tabbarcontrollers, view controllers added as subviews to some other view controllers while traversing), here is my version of returning the currently visible view controller:
=====================================================================
=====================================================================
And now all you need to do to get top most view controller is call the above method as follows: