O'Reilly logo

iOS 7 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

5.6. Handling Events in Collection Views

Problem

You want to be able to handle collection view events, such as taps.

Solution

Assign a delegate to your collection view. In some other cases, you may not even have to do that. All you may need to do is listen for those events in your cell classes and handle them right there.

Discussion

Collection views have delegate properties that have to conform to the UICollectionViewDelegate protocol. The delegate object will then receive various delegation calls from the collection view informing the delegate of various events, such as a cell becoming highlighted or selected. You need to know the difference between the highlighted and selected state of a collection view cell. When the user presses her finger down on a cell in a collection view but doesn’t lift her finger up, the cell under her finger is highlighted. When she presses her finger down and lifts her finger up to say she wants to perform an action on the cell, that cell will then be selected.

Collection view cells of type UICollectionViewCell have two very useful properties, highlighted and selected, that get set to YES when the cell becomes highlighted or selected.

If all you want to do is change your cell’s visual presentation when it becomes selected, you’re in luck, because cells of type UICollectionViewCell expose a property named selectedBackgroundView of type UIView that you can set to a valid view. This view will then get displayed on the screen once your cell becomes selected. Let’s ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required