Remsay
Remsay

Reputation: 331

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.

Upvotes: 30

Views: 46390

Answers (4)

moonvader
moonvader

Reputation: 21091

Or maybe this can be used

self.navigationController.visibleViewController

or

self.navigationController.topViewController

Upvotes: 4

Bogdan Farca
Bogdan Farca

Reputation: 4096

Or as an extension:

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

And then you use it like this:

if let rootv = navigationController?.rootViewController { }

Upvotes: 22

Sameh Salama
Sameh Salama

Reputation: 777

replace

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

with

let homevci = controllerArray.first as? NBHomeVC

or

let homevci = controllerArray[0] as? NBHomeVC

Upvotes: 0

user6083088
user6083088

Reputation: 1037

You can get the root by,

self.navigationController!.viewControllers.first

Upvotes: 51

Related Questions