Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access View Controller from Tab bar controller?

I have a tab bar controller and each tab consist of a navigation controller.

How can I access a specific view controller in a navigation controller in a tab so that I can access a property specific to the view controller?

I tried the following code:

//Get the navigation controller of the 3rd tab
self.tabController.selectedViewController 
= [self.tabController.viewControllers objectAtIndex:2];

//Attempt to retrieve the viewcontroller I want from the tabcontroller
SomeViewController *svc = (SomeViewController *)self.tabController.selectedViewController;

//Attempting to access a BOOLEAN property in svc viewcontroller
svc.someProperty = YES;

The above code failed because it seems that "self.tabController.selectedViewController" returns me a navigation controller. How can I extend the code so that I can access "svc.someProperty"?

like image 443
Zhen Avatar asked Aug 16 '11 06:08

Zhen


3 Answers

You can use -topViewController to get the view controller from the navigation controller (or -visibleViewController if you are using modal view controllers).

like image 151
jtbandes Avatar answered Oct 28 '22 22:10

jtbandes


If self.tabController.selectedViewController is your navigation view controller, then you can access the currently visible controller using:

visibleViewController

and the top view controller using:

topViewController

If this does not allow you to get to SomeViewController, you can iterate through the list of controllers pushed on the navigation controller stack:

viewControllers

like image 36
sergio Avatar answered Oct 28 '22 21:10

sergio


Since the view controller is a subview of the returned UINavigationController(SVC), you could just send it the following method [svc topViewController];. That should return you the view controller and then you should be able to access the property.

like image 31
ms83 Avatar answered Oct 28 '22 22:10

ms83