Extend default interactivePopGestureRecognizer beyond screen edge?

Viewed 2920

I have a UIViewController that gets pushed onto a navigation stack. I'd like to extend the standard iOS7 interactive pan gesture to pop this view controller beyond the default UIRectEdgeLeft boundaries, so that users can initiate an interactive back action by panning from anywhere on the view.

I've tried rolling my own interactive view controller transition, but it's a lot of hassle to fully replicate the nice parallax handling of the default interactivePopGestureRecognizer. For example, the fromViewController hides the navigation bar, while the toViewController shows it—something that is not easy to handle in a custom interactive transition, but is seamless in the default action.

As a result, I want to extend the default action to a larger area of pan gesture, but the API doesn't seem to support simply replacing the gesture.

Any creative suggestions?

2 Answers

It's actually quite easy to do on the UINavigationController subclass without any intervention into every UIViewController subclass pushed. Also respecting built-in swipe-from-edge state (so when it's disabled for some reason, the new gesture is disabled as well):

import UIKit

class NavigationController: UINavigationController {
    override func viewDidLoad() {
        super.viewDidLoad()
        setupFullWidthBackGesture()
    }

    private lazy var fullWidthBackGestureRecognizer = UIPanGestureRecognizer()

    private func setupFullWidthBackGesture() {
        // The trick here is to wire up our full-width `fullWidthBackGestureRecognizer` to execute the same handler as
        // the system `interactivePopGestureRecognizer`. That's done by assigning the same "targets" (effectively
        // object and selector) of the system one to our gesture recognizer.
        guard
            let interactivePopGestureRecognizer = interactivePopGestureRecognizer,
            let targets = interactivePopGestureRecognizer.value(forKey: "targets")
        else {
            return
        }

        fullWidthBackGestureRecognizer.setValue(targets, forKey: "targets")
        fullWidthBackGestureRecognizer.delegate = self
        view.addGestureRecognizer(fullWidthBackGestureRecognizer)
    }
}

extension NavigationController: UIGestureRecognizerDelegate {
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        let isSystemSwipeToBackEnabled = interactivePopGestureRecognizer?.isEnabled == true
        let isThereStackedViewControllers = viewControllers.count > 1
        return isSystemSwipeToBackEnabled && isThereStackedViewControllers
    }
}
Related