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?
Here is what worked for me.
I found that sometimes the controller was nil on the key window, as the keyWindow is some OS thing like an alert, etc.
you could find the top most view controller by using
Another solution relies on the responder chain, which may or may not work depending on what the first responder is:
Example pseudo code:
For latest Swift Version:
Create a file, name it
UIWindowExtension.swift
and paste the following snippet:Use it anywhere as:
This is an improvement to Eric's answer:
_topMostController(UIViewController *cont)
is a helper function.Now all you need to do is call
topMostController()
and the top most UIViewController should be returned!