Adding a swipe gesture recognizer

You can add a UISwipeGestureRecognizer(opens in a new tab) to PDFViewController’s view at any time:

let swipeGestureRecognizer = UISwipeGestureRecognizer()
swipeGestureRecognizer.direction = .left
let pdfViewController = PDFViewController()
pdfViewController.view.addGestureRecognizer(swipeGestureRecognizer)

However, this isn’t enough to make it work. By default, UIKit will prioritize UIScrollView(opens in a new tab)’s panGestureRecognizer(opens in a new tab) over your UISwipeGestureRecognizer(opens in a new tab). To reverse this and allow scrolling to proceed only if your swipe gesture recognizer has failed, you’ll need to set up a failure requirement in both the documentViewController(_:configureScrollView:) and documentViewController(_:configureZoom:forSpreatAt:) delegate methods:

func documentViewController(_ documentViewController: PDFDocumentViewController, configureScrollView scrollView: UIScrollView) {
scrollView.panGestureRecognizer.require(toFail: self.swipeGestureRecognizer)
}
func documentViewController(_ documentViewController: PDFDocumentViewController, configureZoom zoomView: UIScrollView, forSpreadAt spreadIndex: Int) {
zoomView.panGestureRecognizer.require(toFail: self.swipeGestureRecognizer)
}

Don’t forget to consider the experience of scrolling and zooming. If you’re adding a swipe gesture recognizer, consider either disabling scrolling and zooming entirely, or conditionally preventing your swipe gesture recognizer from proceeding. For example, to only allow swiping when zoomed out and still allow panning a page around when zoomed in, you could write the following:

func documentViewController(_ documentViewController: PDFDocumentViewController, configureZoom zoomView: UIScrollView, forSpreadAt spreadIndex: Int) {
zoomView.delegate = self
zoomView.panGestureRecognizer.require(toFail: self.swipeGestureRecognizer)
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
self.lastKnownZoomScale = scrollView.zoomScale
}
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer === self.swipeGestureRecognizer {
return self.lastKnownZoomScale == 1
} else {
return true
}
}

For more details on how to coordinate multiple gesture recognizers, refer to our guide on the document view hierarchy and Apple’s guide on coordinating multiple gesture recognizers(opens in a new tab).