How can I get the rootViewController of UINavigationController
Asked Answered
C

4

29

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.

Cutpurse answered 4/1, 2017 at 14:52 Comment(5)
this is let homevci = navigationController!.viewControllers!.first as! NBHomeVCLambdoid
but better way, you need to read some swift documentation. it is not objc-c :)Lambdoid
#26667509Bryson
It works, thank you , I think I should think about the difference between [UIViewController] and array.Cutpurse
https://mcmap.net/q/159226/-how-do-i-get-the-rootviewcontroller-from-a-pushed-controllerBarramunda
C
51

You can get the root by,

self.navigationController!.viewControllers.first
Cosmotron answered 4/1, 2017 at 14:58 Comment(0)
A
22

Or as an extension:

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

And then you use it like this:

if let rootv = navigationController?.rootViewController { }
Asseverate answered 4/1, 2017 at 14:59 Comment(2)
Nice answer, but as? UIViewController can be removed because first already returns a UIViewController?. Also, in your second code snippet it should be navigationController?.rootViewController as it's an optional.Deepseated
@nyg: Thanks for spotting it, I'm sure it worked at some point in the past, but too many Swift versions came and went ... It should work now in Swift 4.Asseverate
V
4

Or maybe this can be used

self.navigationController.visibleViewController

or

self.navigationController.topViewController
Vitiligo answered 28/2, 2018 at 7:26 Comment(1)
This is not the root view controller , This is the top view controller in the navigation controller stack , topViewController will be the root view controller if the navigation controller did not push any view controllers .Nard
U
0

replace

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

with

let homevci = controllerArray.first as? NBHomeVC

or

let homevci = controllerArray[0] as? NBHomeVC
Unimproved answered 4/1, 2017 at 14:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.