Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you check current view controller class in Swift?

Tags:

ios

swift

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?

like image 612
user83039 Avatar asked Dec 31 '14 03:12

user83039


People also ask

How do I get current ViewController?

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.

How do I know if ViewController is visible?

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.

How do I present a controller in Swift?

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.


2 Answers

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 } 
like image 135
mc01 Avatar answered Sep 25 '22 19:09

mc01


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         }     } 
like image 26
Nhut Duong Avatar answered Sep 22 '22 19:09

Nhut Duong