skip to Main Content

Let say I have 3 View Controllers VC1, VC2 and VC3. The first View Controller is VC1, from this i’ll go to VC2 and from VC2 i’ll go to VC3. The question is how can I back from VC3 -> VC1 not VC3 -> VC2 -> VC1 while using Swipe Back.

NOTE:

This is Question about Swipe Back, not clicked Back Button as manually.

Here’s My Codes:

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()
        // do something
    }
    
    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 PKNavigationController: UINavigationControllerDelegate, UIGestureRecognizerDelegate {
    func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
        // Do Something
    }
    
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
}

2

Answers


  1. In VC3, whenever you want to go back use:

    navigationController?.popToRootViewController(animated: true)
    
    Login or Signup to reply.
  2. It’s not entirely clear what you want from your question, but if you mean that you want both the back button and the swipe back gesture to go back from VC3 to VC1 as if VC2 wasn’t in the navigation stack, then: after VC2 pushes VC3, use UINavigationController‘s setViewControllers:animated: to [vc1, vc3], animated false. Then there’s only 2 vc’s on the nav stack and back button and swipe gesture will both go back to vc1.

    This may be a strange experience for the user of course because this isn’t how nav stacks are meant to work (where did vc2 disappear?), so perhaps you would be better off with VC1 pushing some kind of container VC that transitions between VC2 and VC3 without pushing.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search