如何通过侧滑返回直接从VC3回到VC1而非逐级返回?
实现VC3侧滑直接返回VC1的方案
需求:导航流程为VC1→VC2→VC3,需实现侧滑返回操作直接从VC3回到VC1,而非按VC3→VC2→VC1逐级返回。
核心思路
系统默认的interactivePopGestureRecognizer仅支持返回上一级页面,要实现跨级侧滑返回,需做以下处理:
- 监听侧滑手势的触发时机,判断当前页面是否为VC3
- 当处于VC3时,触发
popToViewController(_:animated:)直接回到VC1,保留侧滑动画的连贯性 - 其他页面维持默认的侧滑返回逻辑
修改后的完整代码
class MyNavigationController: UINavigationController { override init(rootViewController: UIViewController) { super.init(rootViewController: rootViewController) self.delegate = self interactivePopGestureRecognizer?.delegate = self navigationBar.isTranslucent = false view.backgroundColor = .white } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() // 可在此添加自定义初始化逻辑 } override func pushViewController(_ viewController: UIViewController, animated: Bool) { super.pushViewController(viewController, animated: animated) interactivePopGestureRecognizer?.isEnabled = false } func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) { interactivePopGestureRecognizer?.isEnabled = true } } extension MyNavigationController: UINavigationControllerDelegate, UIGestureRecognizerDelegate { func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { // 页面切换前的自定义逻辑可在此实现 } func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { // 判断是否触发系统侧滑手势,且当前为VC3、栈中存在VC1 guard gestureRecognizer == interactivePopGestureRecognizer, let topVC = viewControllers.last, topVC is VC3, let targetVC = viewControllers.first(where: { $0 is VC1 }) else { // 其他场景保持默认逻辑:栈内页面数>1时允许侧滑返回上一级 return viewControllers.count > 1 } // 执行直接返回VC1的操作 popToViewController(targetVC, animated: true) // 返回false阻止系统默认的返回上一级行为 return false } }
关键说明
- 手势触发判断:在
gestureRecognizerShouldBegin方法中,精准识别系统侧滑手势、当前页面身份及目标页面是否存在。 - 跨级返回实现:调用
popToViewController(_:animated:)直接跳转至VC1,开启动画保证侧滑体验的流畅性。 - 默认行为拦截:返回
false避免系统执行默认的返回VC2操作。 - 兼容其他页面:非VC3场景维持系统原生侧滑逻辑,保证正常的逐级返回体验。
注意事项
- 确保VC1、VC2、VC3的类型判断准确,若通过故事板初始化页面,需保证类型匹配。
- 若需要更精细的手势控制(如根据侧滑距离/速度触发),可在
gestureRecognizerShouldBegin中添加额外的手势状态判断。
内容的提问来源于stack exchange,提问作者Rilwanul Huda
相关产品推荐
相关产品推荐

