Reputation: 171
I have setup a tab bar view controller and linked with navigation controller,
refer to this image.
The issue I'm facing is this image is "more" tab bar page
when I click the cross button, it will push to home view controller to another view. But when I hit another tab and come back to more tab, the view controller stil stay at the home view controller instead of more tab origin controller. I need to hit more tab 2 times then it only will back to more tab view controller. Below code is my tab bar controller when selecting item.
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
NSLog(@"didSelectItem: %ld", (long)item.tag);
if (item.tag == 0) {
//try to dismiss home view controller in this way, but it won't work
[self.navigationController popToRootViewControllerAnimated:YES];
NSString *str = @"TAB 1";
NSLog(@"%@", str);
}
}
Upvotes: 2
Views: 1200
Reputation: 57
Just add this method to UITabBarControllerDelegate
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem){enter following code in this method}
if item.tag < self.viewControllers!.count {
if let nav = self.viewControllers![item.tag] as? UINavigationController {
nav.popToRootViewController(animated: true)
}
}
Upvotes: 0
Reputation: 404
Updated answer for Swift 4.1 iOS 11.2
class TabBarMenuView: UITabBarController {
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
if (self.selectedViewController?.isKind(of: UINavigationController.self))!
{
let nav = self.selectedViewController as! UINavigationController
nav.popToRootViewController(animated: false)
}
}
}
Upvotes: 1
Reputation: 8322
Try this :
Conform protocol on appdelegte or subclass of UITabViewController
<UITabBarControllerDelegate>
Assign delegate
tabBarController.delegate = self
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
if ([viewController isKindOfClass:[UINavigationController class]])
{
[(UINavigationController *)viewController popToRootViewControllerAnimated:NO];
}
}
Upvotes: 1