I'm trying to get the currently display UIViewController
that is not in the AppDelegate, but it seems to always get the initial top UIViewController
, and not the present one.
The following code in AppDelegate DOES get the current UIViewController
present, but this same function does not work when I use it in any one of my View Controllers:
func getTopViewController() -> UIViewController
{
var topViewController = UIApplication.sharedApplication().delegate!.window!!.rootViewController!
while (topViewController.presentedViewController != nil) {
topViewController = topViewController.presentedViewController!
}
return topViewController
}
The above code was provided as an answer in a similar question: Get the current displaying UIViewController on the screen in AppDelegate.m
No matter how deep down I segue to, I can only retrieve the first-most View Controller.
How can I get the current presenting UIViewController
?
FYI: I'm NOT using a UINavigationController
, just regular UIViewController
classes.
I do not like using this but sometimes it is necessary.
**EDIT:
Here is an improved version, it will always get top most view controller
Here is the same idea in one function:
works for me in Swift 4 project