How can I get rootViewController UINavigationController in Swift

I want to get rootViewController from UINavigationController, it works in Objective-c, but when I use it in Swift, the error reminds me that it was not correct to enter the image description here .

If I do, add “as! NSArray”, it works, but also reminds me that “other than [UIViewController]” to the unrelated type “NSArray” always fails. " enter image description here

Can someone show the best way to get rootViewController without errors or reminds? Thanks.

+7
ios swift
source share
4 answers

You can get the root

self.navigationController!.viewControllers.first 
+11
source share

Or as an extension:

 extension UINavigationController { var rootViewController : UIViewController? { return viewControllers.first } } 

And then you use it like this:

 if let rootv = navigationController?.rootViewController { } 
+9
source share

Or maybe it can be used

 self.navigationController.visibleViewController 

or

 self.navigationController.topViewController 
+1
source share

replace

 let homevci = controllerArray.objectAtIndex(0) as? NBHomeVC 

from

 let homevci = controllerArray.first as? NBHomeVC 

or

 let homevci = controllerArray[0] as? NBHomeVC 
0
source share

All Articles