Fuad Adetoro
Fuad Adetoro

Reputation: 137

Swift Navigation Controller swipe to go back anywhere

I have a view controller with an embedded Navigation Controller and I want the presented controller to be able to swipe anywhere to return back to the root controller. How is this possible is it by using SwipeGesture or Extending the navigation controller?

Also please note that the presented controller is a table view and has cell nibs.

Upvotes: 3

Views: 6786

Answers (2)

agentpietrucha
agentpietrucha

Reputation: 1

I deleted all viewControllers from navigationController except the one currently displayed and the one I want to go back to with swipe.

My viewControllers hierarchy: AViewController -> BViewController -> CViewController

Let's say I am currently displaying CViewController and want to swipe back to go to AViewController. By default, when swiping back from CViewController I would go back to BViewController, which is preceding CViewController. So when CViewController is on display I delete BViewController from navigationController and I can nicely swipe back to AViewController

self.navigationController?.viewControllers.removeAll {
  !($0 is AViewController) && !($0 is CViewController)
}

Upvotes: 0

Giuseppe Lanza
Giuseppe Lanza

Reputation: 3699

Based on your indications a normal gesture recognizer on your tableview is enough.

I would do something like this:

override func viewDidLoad() {
    super.viewDidLoad()

    let gesture = UISwipeGestureRecognizer(target: self, action: #selector(dismiss(fromGesture:)))
    tableView.addGestureRecognizer(gesture)
}

@objc func dismiss(fromGesture gesture: UISwipeGestureRecognizer) {
    //Your dismiss code
    //Here you should implement your checks for the swipe gesture
}

And if you want to disable the default behavior of the back gesture:

navigationController?.interactivePopGestureRecognizer?.isEnabled = false

I hope it helped. :)

Upvotes: 6

Related Questions