You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现点击已选中的CustomTabBarController标签页不切换页面?

自定义TabBarController保留当前导航页面的解决方案

默认情况下,UITabBarController点击当前已选中的标签页时,会自动将该标签对应的导航控制器pop到根视图控制器。要实现点击当前标签页时停留在子页面B,需要覆盖这个默认行为,以下是两种可行方案:

方法一:利用UITabBarControllerDelegate拦截选择行为

在你的CustomTabBarController中设置自身为代理,实现以下代理方法,阻止默认的回退到根控制器行为:

Objective-C 实现

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
    // 判断是否点击的是当前已选中的标签页
    if (viewController == self.selectedViewController) {
        UINavigationController *nav = (UINavigationController *)viewController;
        // 若导航栈页面数大于1(存在子页面B),返回NO阻止默认的pop到根操作
        return nav.viewControllers.count <= 1;
    }
    // 切换其他标签页时正常执行
    return YES;
}

Swift 实现

func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
    guard let selectedVC = tabBarController.selectedViewController, selectedVC == viewController else {
        return true
    }
    guard let nav = viewController as? UINavigationController else {
        return true
    }
    // 只有当导航栈只有根页面时,才允许默认行为
    return nav.viewControllers.count <= 1
}

方法二:重写CustomTabBarController的选择方法

直接在自定义的CustomTabBarController子类中重写selectViewController:方法,覆盖默认逻辑:

Objective-C 实现

- (void)selectViewController:(UIViewController *)viewController {
    if (self.selectedViewController == viewController) {
        UINavigationController *nav = (UINavigationController *)viewController;
        // 存在子页面时,不执行默认的pop操作
        if (nav.viewControllers.count > 1) {
            return;
        }
    }
    // 正常情况执行父类方法
    [super selectViewController:viewController];
}

Swift 实现

override func selectViewController(_ viewController: UIViewController?) {
    guard let targetVC = viewController, targetVC == selectedViewController else {
        super.selectViewController(viewController)
        return
    }
    guard let nav = targetVC as? UINavigationController, nav.viewControllers.count > 1 else {
        super.selectViewController(viewController)
        return
    }
    // 存在子页面时,跳过父类的默认逻辑
}

注意事项

  • 确保第3个标签页对应的控制器是UINavigationController,页面A是其根控制器,页面B通过pushViewController:animated:方式进入。
  • 若需要在点击当前标签且处于根页面时执行额外操作(如刷新页面A),可在上述判断的else分支中添加对应逻辑。

内容的提问来源于stack exchange,提问作者Louiza A

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 22:42:58