Search code examples
iosswiftswift4uipangesturerecognizer

UIPanGestureRecognizer to pop UIViewController


I'm wondering if it is actually possible to use a UIPanGestureRecognizer on a pushed UIViewController to achieve a similar behaviour like in the Telegram messenger chat view (and a lot of other popular Apps), where you can simply swipe to the right from anywhere on the screen to get back to the menu (or any other View Controller that initially pushed the one we are looking at).
I tried this code:

    @objc func swipeLeft(_ sender: UIPanGestureRecognizer) {
    let point = sender.translation(in: view)
    containerView.center = CGPoint(x: point.x > 0 ? view.center.x + point.x : view.center.x, y: view.center.y)
    if sender.state != .ended { return }

    if containerView.center.x < view.frame.width / 2 {
        dismissSelf()
    }
    else {
        UIView.animate(withDuration: 0.2) {
            self.containerView.center = self.view.center
        }
    }
}

and a UIPanGestureRecognizer, which does work nicely if you presented your ViewController but not when it is pushed. At least not how it is right now.

Right now, you see a black view and that's also what you see in the "Debug View Hirachy" at the bottom of a pushed UIViewController.

Any help is appreciated!


Solution

  • I think what you are looking for is already built-in with the interactivePopGestureRecognizer

    self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
    

    if you want to make some custom or different animation then I think you need to check transitions. Here's a good article to make custom transitions: https://medium.com/swift2go/simple-custom-uinavigationcontroller-transitions-fdb56a217dd8