Honghao Z
Honghao Z

Reputation: 1527

How to get tabBarController in one of its viewController when using storyboard?

I make a Tabbed Application using storyboard template, two view controllers are embedded.

This is what I want to do: in the first viewController, let TabBar to select the second viewController programmatically.

The first viewController is a tableViewController, shows a list of items, and each item will push to a detailViewController. In the detailViewController, I edit some information and save the item. Then I want app to show the second ViewController, which is a tableViewController shows saved item.

Usually, we can use [TabBarController setSelectedIndex:1]; to select the second viewController.

However, since this is a storyboard template application, so many code are hidden behind. So I cannot get the TabBar instance in the first viewController, and use setSelectedIndex method.

This is what confuses me...

And now, I have found the solution for this problem. My answer is below.

Upvotes: 0

Views: 2631

Answers (1)

Honghao Z
Honghao Z

Reputation: 1527

I have figured out how to solve this problem.

First I add new a class: MyTabBarController.

Then, in storyboard, select the Tab Bar Controller, in identity inspector panel, set the custom class to this new class.

For the first viewController class, add a property

@property (nonatomic, weak) UITabBarController *tabBarController;

Then add - (void)viewDidAppear:(BOOL)animated in MyTabBarController class:

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    UINavigationController *navigationController = [self.viewControllers objectAtIndex:0];
    FirstViewController *firstViewController = (FirstViewController *)navigationController.topViewController;
    firstViewController.tabBarController = self;

In this way, I pass the tabBarController instance to the firstViewController, so, in the firstViewController, I can call [tabBarController setSelectedIndex:1];

Storyboard gives me a visual interface, however, it hides so many things behind.

Upvotes: 2

Related Questions