Reputation: 84
How can I detect a swipe on a Page View Controller even if there aren't any view controllers left to swipe through?
Upvotes: 1
Views: 2651
Reputation: 122
The Page View Controller has a built in gesture recognizer contained within the scrollView. It's a pan gesture recognizer (see https://developer.apple.com/documentation/uikit/uiscrollview/1619425-pangesturerecognizer). However, the scroll view property of the Page View Controller is not public (see https://developer.apple.com/documentation/uikit/uipageviewcontroller). You could extend the Page View Controller class to alter this behavior and expose the scroll view in order to get the pan gestures that continue to occur after the user has scrolled through all of the available views.
extension UIPageViewController {
public var scrollView: UIScrollView? {
for view in self.view.subviews {
if let scrollView = view as? UIScrollView {
return scrollView
}
}
return nil
}
}
Next you should add your root view controller as a target of the scroll view's pan gesture in your view did load method and include the method you would like to call when the scroll view's gesture recognizer detects a pan gesture. You can track the number of swipes with a property stored on your root view controller as well. Note that if you want to track the swipes beyond the final view controller you'll need to set up a bool property on your root view controller that gets set to true after the user swipes to the final view in the page view controller and only start tracking swipes after this threshold is met.
override func viewDidLoad() {
. . .
pvController.scrollView?.panGestureRecognizer.addTarget(self, action:#selector(self.handlePan(sender:)))
}
func handlePan(sender:UIPanGestureRecognizer) {
switch sender.state {
case .ended:
self.numberOfSwipes = self.numberOfSwipes + 1
print("User Swiped ")
print(self.numberOfSwipes)
default:
break
}
}
You probably want to set up a bool property on your view controller that gets triggered after the user consumes all of the views so that you know the swipe is one that occurs beyond the views. I placed the code for the app in a public repo at https://bitbucket.org/stonybrooklyn/pageviewcontroller/ for your reference.
Upvotes: 1