Tip

How to Use the UINavigationController Swipe Back Gesture with a UIPageViewController

I’ve been working on an app at work that’s “Snapchat-eqsue” (uses a UIPageViewController to page between a full-screen camera and a UINavigationController) when I came across this conundrum. Basically, the app is setup as follows:

Please excuse the poor lighting and shoddy sketch. It's early and I didn't feel like opening Sketch.
Please excuse the poor lighting and shoddy sketch. It’s early and I didn’t feel like opening Sketch.

So the Camera is the leftmost view in the PageViewController and the UINavigationController, along with all the views it will add to its stack, is on the right. Things got a bit tricky though when our designer wanted to avoid using physical back buttons on the navigation stack and have the traditional swipe back take you to the previous page. My first instinct was to intercept the PageController gestures, but when it’s set to scrolling, those don’t actually exist–the gesture array comes up empty. That’s when I came up with this fun little hack that’s incredibly easy to do.

The tl;dr is you disable the UIPageViewController’s UIScrollView when the NavigationController displays any view that’s not the root view controller and add a swipe gesture recognizer to each of the subviews. While this sounds like a lot of tedious work, it’s actually really easy if you just subclass UIViewController and use that app-wide (which is actually nice for a variety of reasons like themeing–but that’s for another post).