Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the rootViewController of UINavigationController

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.

like image 477
Remsay Avatar asked Jan 04 '17 14:01

Remsay


3 Answers

You can get the root by,

self.navigationController!.viewControllers.first
like image 170
user6083088 Avatar answered Dec 01 '22 00:12

user6083088


Or as an extension:

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

And then you use it like this:

if let rootv = navigationController?.rootViewController { }
like image 35
Bogdan Farca Avatar answered Nov 30 '22 23:11

Bogdan Farca


Or maybe this can be used

self.navigationController.visibleViewController

or

self.navigationController.topViewController
like image 35
moonvader Avatar answered Dec 01 '22 01:12

moonvader