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.

Chris
  • 4,009
  • 3
  • 21
  • 52
Remsay
  • 321
  • 1
  • 3
  • 4

4 Answers4

51

You can get the root by,

self.navigationController!.viewControllers.first
user6083088
  • 1,047
  • 1
  • 9
  • 27
21

Or as an extension:

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

And then you use it like this:

if let rootv = navigationController?.rootViewController { }
Bogdan Farca
  • 3,856
  • 26
  • 38
  • 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. – nyg Jun 15 '17 at 08:59
  • @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. – Bogdan Farca Jun 16 '17 at 13:46
4

Or maybe this can be used

self.navigationController.visibleViewController

or

self.navigationController.topViewController
moonvader
  • 19,761
  • 18
  • 67
  • 116
  • 2
    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 . – mazen Jun 20 '20 at 06:34
0

replace

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

with

let homevci = controllerArray.first as? NBHomeVC

or

let homevci = controllerArray[0] as? NBHomeVC
Sameh Salama
  • 765
  • 1
  • 7
  • 17