As far as I know, this would work in Objective-C:
self.window.rootViewController.class == myViewController
How can I check if the current view controller is a specific one?
You can now call visibleViewController on UIWindow and this will get you the visible view controller by searching down the controller hierarchy. This works if you are using navigation and/or tab bar controller. If you have another type of controller to suggest please let me know and I can add it.
The view's window property is non-nil if a view is currently visible, so check the main view in the view controller: Invoking the view method causes the view to load (if it is not loaded) which is unnecessary and may be undesirable. It would be better to check first to see if it is already loaded.
To present a ViewController in a NavigationController you can wrap ViewController into a NavigationController as it is in the example below. Then present NavigationController which contains ViewController. Check out the below video courses to learn more about Mobile App Development for iOS platform with Swift.
To check the class in Swift, use "is" (as explained under "checking Type" in the chapter called Type Casting in the Swift Programming Guide)
if self.window.rootViewController is MyViewController { //do something if it's an instance of that class }
Updated for swift3 compiler throwing a fit around ! and ?
if let wd = UIApplication.shared.delegate?.window { var vc = wd!.rootViewController if(vc is UINavigationController){ vc = (vc as! UINavigationController).visibleViewController } if(vc is LogInViewController){ //your code } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With