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.sel开发者_Go百科ectedViewController" returns me a navigation controller. How can I extend the code so that I can access "svc.someProperty"?
You can use -topViewController
to get the view controller from the navigation controller (or -visibleViewController
if you are using modal view controllers).
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
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.
精彩评论