Nur II
Nur II

Reputation: 171

Tab bar controller need to tap 2 times return main view

I have setup a tab bar view controller and linked with navigation controller,
refer to this image.
enter image description here
The issue I'm facing is this image is "more" tab bar page
enter image description here
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

Answers (3)

Crack_Code
Crack_Code

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

rudald
rudald

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

KKRocks
KKRocks

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

Related Questions