Zhen
Zhen

Reputation: 12431

How to get the 'current' navigation controller from tab bar controller

Is there is a method to retrieve tab bar controller's current visible navigation controller?

For example, I have 2 tabbars in my program (one navigation controller each) as below

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url 
{   
   //Method is called when user clicks on a hyperlink in one of view controllers
    NSDictionary *dict = [self parseQueryString:[url query]];
    NSString *userID = [dict objectForKey:@"id"];
    NSString *navconTitle = [dict objectForKey:@"navcon"];


    //intention is to push a view controller onto the CURRENT navigation stack
    [navcon pushViewController:someViewController animated:YES];

    }
}

return YES;
}

Can anyone advise me how I can determine the current navigation controller so that I can push more viewcontrollers onto it?

Upvotes: 20

Views: 33805

Answers (4)

David
David

Reputation: 101

Updating Starsky's Swift answer to iOS 13 ("'keyWindow' was deprecated in iOS 13.0")

guard let tabBarVC = UIApplication.shared.windows.filter({$0.isKeyWindow}).first?.rootViewController as? UITabBarController else { return }
    if let currentNavController = tabBarVC.selectedViewController as? UINavigationController {
...
}

Upvotes: 6

Starsky
Starsky

Reputation: 2048

A Swift version, in case someone can't read Objective-C, with an additional solution for how to find the tabBar from anywhere. I use this to push to a screen when processing a notification.

guard let tabBarVC = UIApplication.shared.keyWindow?.rootViewController as? UITabBarController else { return }

if let currentNavController = tabBarVC.selectedViewController as? UINavigationController {
    currentNavController.pushViewController(someVC, animated: true)
}

Upvotes: 2

Adrian B
Adrian B

Reputation: 418

I think UITabBarController selectedViewController property should be what you are looking for.

So, from a UITabBarController method :-

 [self.selectedViewController pushViewController:someViewController animated:YES];

Upvotes: 4

Joe
Joe

Reputation: 57179

Use the UITabBarControllers selectedViewController property.

navcon = (UINavigationController*)myTabBarController.selectedViewController;
[navcon pushViewController:someViewController animated:YES];

Upvotes: 71

Related Questions