5.8. Adding Custom Interactions to Collection Views

Problem

You want to add your own gesture recognizers, such as pinch gesture recognizers, to a collection view in order to enable custom behaviors on top of the existing ones.

Solution

Instantiate your gesture recognizer and then go through all the existing collection view gesture recognizers to see whether a gesture recognizer similar to yours already exists. If so, call the requireGestureRecognizerToFail: method on the existing gesture recognizer and pass your own recognizer as the parameter to this method. This will ensure that the collection view’s gesture recognizer that is similar to yours will grab the gestures only if your gesture recognizer fails to process its data or its requirements/criteria aren’t met. That means that if your gesture recognizer can process the gesture, it will, but if it cannot, the gesture will be sent to the collection view’s existing gesture recognizers for processing.

Once this is done, add your gesture recognizer to your collection view. Remember, in an instance of UICollectionViewController, your collection view object is accessible through the collectionView property of the controller and not the view property.

Discussion

The iOS API has already added a few gesture recognizers to collection views. So in order to add your own gesture recognizers, on top of the existing collection, you first need to make sure that your gesture recognizers will not interfere with the existing ones. To do that, you have ...

Get iOS 7 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.