How can I get the rootViewController of UINavigationController

Remsay picture Remsay · Jan 4, 2017 · Viewed 40k times · Source

I want to get the rootViewController of UINavigationController. It works in Objective-c, but when I use it in Swift , the error reminds me that it was wrong.

Code screenshot 1.

If I do this, add as! NSArray, it works, but also reminds me that "cast from '[UIViewController]' to unrelated type 'NSArray' always fails".

Code screenshot 2

Can somebody show a better way to get the `rootViewController`` without error. Thank you.

Answer

user6083088 picture user6083088 · Jan 4, 2017

You can get the root by,

self.navigationController!.viewControllers.first