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?
iOS 4 introduced the rootViewController property on UIWindow:
You'll need to set it yourself after you create the view controller though.
I think most of the answers have completely ignored
UINavigationViewController
, so I handled this use case with following implementation.If the root controller is a navigation controller, correct way to find top visible controller is:
Here's an excerpt from UINavigationController.h:
Simple extension for
UIApplication
in Swift:NOTE:
It cares about
moreNavigationController
withinUITabBarController
Simple usage:
This solution is the most complete. It takes in consideration: UINavigationController UIPageViewController UITabBarController And the topmost presented view controller from the top view controller
The example is in Swift 3.
There are 3 overloads
I recently got this situation in one my project, which required to displayed a notification view whatever the controller displayed was and whatever was the type (UINavigationController, classic controller or custom view controller), when network status changed.
So I juste released my code, which is quite easy and actually based on a protocol so that it is flexible with every type of container controller. It seems to be related with the last answers, but in a much flexible way.
You can grab the code here : PPTopMostController
And got the top most controller using