双击UITabBarController时防止自动popToRootViewController

问题描述 投票:32回答:5

UITabBarController的默认行为是在第二次点击特定选项卡时将包含的UINavigationController弹出到根视图控制器。我有一个特殊的用例,我希望它不能自动工作,而我很难弄清楚如何防止这种情况。

有没有人碰到这个,如果有的话,你做了什么?我是否需要子类化UINavigationController并覆盖popToRootViewController或者是否有更简单的方法?

iphone uinavigationcontroller uitabbarcontroller
5个回答
63
投票

使用tabBarController:shouldSelectViewController:UITabBarControllerDelegate protocol方法。

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
    return viewController != tabBarController.selectedViewController;
}

不要忘记将标签栏控制器的委托设置为实际实现此委托方法的对象。


14
投票

这就是我做的:

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController 
{

    if ([[tabBarController viewControllers] objectAtIndex:[tabBarController selectedIndex]] == viewController)

            return NO;

    return YES;

}

问候


2
投票

更新Swift 4.1

停止双击所有选项卡。

extension TabBarController: UITabBarControllerDelegate {
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
    //for blocking double tap on all tabs.
    return viewController != tabBarController.selectedViewController
}}

停止双击仅在一个特定选项卡上。这是第三个标签。

extension TabBarController: UITabBarControllerDelegate {
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
    //for blocking double tap on 3rd tab only
    let indexOfNewVC = tabBarController.viewControllers?.index(of: viewController)
    return ((indexOfNewVC != 2) ||
        (indexOfNewVC != tabBarController.selectedIndex))       
}}

希望能帮助到你...

谢谢!!!


1
投票

这种行为有点奇怪,但在深层次结构的情况下是一个方便的快捷方式!

您可以实现以下UITabBarControllerDelegate方法来禁用此系统范围的快捷方式:

#pragma mark -
#pragma mark UITabBarControllerDelegate

- (BOOL)tabBarController:(UITabBarController *)tbc shouldSelectViewController:(UIViewController *)vc {
    UIViewController *tbSelectedController = tbc.selectedViewController;

    if ([tbSelectedController isEqual:vc]) {
        return NO;
    }

    return YES;
}

0
投票

这是Swift 3版本:

func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
    return viewController != tabBarController.selectedViewController
}
© www.soinside.com 2019 - 2024. All rights reserved.