James
James

Reputation:

How to switch tabs and pushViewController at the same time?

I have two tabs in my app, the left tab is a normal UIViewController, right tab is a navigation controller with a table view inside it. I'd like to allow the user to press a button on the left tab and jump to a specific detail view that belongs to a specific row in the table view on the right tab.

In the table view itself I have no problems displaying a specific detail view eg:

[self.navigationController pushViewController:theView animated:YES];

and I can also jump tabs using

self.tabBarController.selectedIndex = 1; // 1= right tab

but I cant figure out how to do both. I've tried

self.tabBarController.selectedIndex = 1; // 1= right tab
// alloc and init theView here
[self.navigationController pushViewController:theView animated:YES];

but that doesnt work.

EDIT:

when I try the above code it just switches tab but doesnt push the view.

I also tried what criscokid suggested but nothing happens at all.

EDIT 2:

Trying to explain whats on each tab:

Root (Tab Bar Controller)  
|  
--(Left Tab)-- UIViewController (I want to go from here...)  
|  
--(Right Tab)---UINavigationController  
             |  
             ---UITableViewController  
                 |  
                 ----UIViewController (...to here) 
                      ^ specific view with data from specific row
                        in table view (that is 'theView' from above)

Upvotes: 3

Views: 3823

Answers (2)

negersiu
negersiu

Reputation: 562

For me the correct way was:

 UINavigationController * navigationController = (UINavigationController *) [[self tabBarController] selectedViewController];
 [navigationController pushViewController:viewController animated:YES];

criscokid's answer has one redundant call to navigationController. That's because your selectedViewController is actually a UINavigationViewController.

Upvotes: 4

criscokid
criscokid

Reputation: 640

If you are switching the tab bar and pushing the ViewController onto the navigation controller stack in the same method, you wouldn't want to use self.navigationController. If I understand correctly you want to add it to a navigationController on the right tab. I believe you would want to use:

[[[[self tabBarController] selectedViewController] navigationController] pushViewController:theView animated:YES];

Upvotes: 1

Related Questions