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?
To complete JonasG's answer (who left out tab bar controllers while traversing), here is my version of returning the currently visible view controller:
And another Swift solution
This answer includes
childViewControllers
and maintains a clean and readable implementation.Great solution in Swift, implement in AppDelegate
Here is my take on this. Thanks to @Stakenborg for pointing out the way to skip getting UIAlertView as the top most controller
A lot of these answers are incomplete. Although this is in Objective-C, this is the best compilation of all of them that I could put together for right now, as a non-recursive block:
... Link to gist, in case it gets revised: https://gist.github.com/benguild/0d149bb3caaabea2dac3d2dca58c0816
... Code for reference/comparison: