You just need to add the UISwipeGestureRecognizer to the main controller view. The master view controller will be responsible for managing gesture calls.
Mostly in code:
in viewDidLoad :
let swipeToLeft = UISwipeGestureRecognizer(target: self, action:
Since you will need to move from VC by index to another index, you may need a property to track the currently selected view controller:
var currentIndexPath: IndexPath?
And you can change its value every time a new VC is selected. So:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { print("You selected cell #\(indexPath.item)!") self.currentIndexPath = indexPath
add the changePageOnSwipe(_ gesture: UISwipeGestureRecognizer) to your main ViewController. Since this is the "main" view controller that collectionView has, it will handle swipes and tell its children:
func changePageOnSwipe(_ gesture: UISwipeGestureRecognizer) { guard let indexPath = self.currentIndexPath else {
and since you are scrolling programmatically, you need to make sure that the swipe is valid before trying to move. You must add security checks :
func canPresentPageAt(indexPath: IndexPath) -> Bool {
Finally, you can set the default indexPath index for self.currentIndexPath to viewDidLoad so that the user can already viewDidLoad when it lands on your main VC without selecting another VC in the collection.
Note. If you have gesture recognizers in sub-ViewControllers, some gestures may conflict, and you will need to learn how to resolve such conflicts using delegate methods such as gestureRecognizer(_:shouldRequireFailureOf:) .
source share