Home > Software engineering >  How can I swipe back to my First View Controller
How can I swipe back to my First View Controller

Time:09-12

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
    }
}

CodePudding user response:

In VC3, whenever you want to go back use:

navigationController?.popToRootViewController(animated: true)

CodePudding user response:

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.

  • Related