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.
You can get the root
self.navigationController!.viewControllers.first
Or as an extension:
extension UINavigationController { var rootViewController : UIViewController? { return viewControllers.first } }
And then you use it like this:
if let rootv = navigationController?.rootViewController { }
Or maybe it can be used
self.navigationController.visibleViewController
or
self.navigationController.topViewController
replace
let homevci = controllerArray.objectAtIndex(0) as? NBHomeVC
from
let homevci = controllerArray.first as? NBHomeVC
let homevci = controllerArray[0] as? NBHomeVC