Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access sub view controllers from Tab Bar Controller

Tags:

ios

swift

swift3

This seems like such a dumb question but I can't quite figure it out:

My storyboard looks like: TabBarController -> Navigation Controller -> Table View Controller 1 -> Table View Controller 2.

This code is located in the Tab Bar Controller and I am trying to access Table View Controller 2

So the way that I understand it, this gets me the Navigation Controller

let tempNavVC = self.viewControllers?[0] as! UINavigationController 

And this should get me the Table View Controller 2 as I think it is index 1 of tempNavVC's viewControllers array.

let secondVC = tempNavVC.viewControllers[1] as! TableViewController2

However, it is clearly not because I am getting:

'NSRangeException', reason: '*** -[__NSSingleObjectArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'

Any help would be greatly appreciated.

like image 283
noblerare Avatar asked Sep 11 '25 11:09

noblerare


2 Answers

The storyboard describes relationships, but it does not describe runtime reality. A pushed view controller (like your second table view controller) is something that can exist if the push happens, but it is not necessarily something that does exist.

Thus, tempNavVC.viewControllers[1] will work if the navigation view controller has two children, i.e. if the second table view is in fact showing in the interface right now. But if only the first of its table view controller children is there, it won't (because the second one has not yet been instantiated and pushed onto the navigation view controller).

like image 199
matt Avatar answered Sep 14 '25 02:09

matt


let navC = tabbarController.viewcontrollers[0] as! UINavigationController
let tableC: UIViewController = navC.rootViewController

....

like image 39
J. Sue Avatar answered Sep 14 '25 01:09

J. Sue