I can't seem to get the top most UIViewController
without access to a UINavigationController
. Here is what I have so far:
UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(vc, animated: true, completion: nil)
However, it does not seem to do anything. The keyWindow
and rootViewController
seem to be non-nil values too, so the optional chaining shouldn't be an issue.
NOTE: It is a bad idea to do something like this. It breaks the MVC pattern.
Usage:
For swift4 to find topmost viewController
How to use
Slight Variation on @AlberZou using a computed variable rather than a function
Then say
presentViewController
shows a view controller. It doesn't return a view controller. If you're not using aUINavigationController
, you're probably looking forpresentedViewController
and you'll need to start at the root and iterate down through the presented views.For Swift 3+:
Where did you put the code in?
I try your code in my demo, I found out, if you put the code in
will fail, because key window have been setting yet.
But I put your code in some view controller's
It just works.
Based on Bob -c above:
Swift 3.0