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.
I loved @dianz's answer, and so here is the swift 3's version of it. It's basically the same thing but his was missing a curly brace and some of the syntax/variable/method names have changed. So here it is!
Usage is still the exact same though:
https://gist.github.com/db0company/369bfa43cb84b145dfd8 I did some tests on the answers and comments on this site. For me, the following works
Then, get the top viewController by:
To find the visible viewController in Swift 3
This code find the last added or the last active controller visible.
This I have used in AppDelegate to find active view Controller
you can define a UIViewController variable in AppDelegate, and in every viewWillAppear set the variable to self.(however dianz answer is the best answer.)
have this extension
Swift 2.*
Swift 3
You can you use this anywhere on your controller
Based on Dianz answer, the Objective-C version