5.9. Providing Contextual Menus on Collection View Cells
Problem
You want to provide a menu to the user when she long-presses an item in your collection view. Through this menu, she may then be able to copy an item, move an item, etc.
Solution
Contextual menus are built into collection views by default. To
enable them, all you have to do is implement the following methods from
the UICollectionViewDelegate
protocol:
collectionView:shouldShowMenuForItemAtIndexPath:
The runtime passes the method an index path to an item. The method returns a Boolean value indicating whether you want the collection view to display the contextual menu for that item or not.
collectionView:canPerformAction:forItemAtIndexPath:withSender:
The runtime passes the method a selector of type
SEL
. You can check the selector (usually by converting it to a string and then comparing it to a string representing the action) and find out whether you want to allow that action to happen. ReturnYES
to allow the action to happen andNO
to suppress it. Remember that you can always convert a selector to a string using theNSStringFromSelector
method. A typical selector could becopy:
orpaste:
for the copy and the paste contextual menu items.collectionView:performAction:forItemAtIndexPath:withSender:
Here you will perform the action that you allowed the collection view to display to the user through earlier delegate methods.
Discussion
Without waiting around, we are going to extend the code that we wrote in Recipe 5.5 and allow a ...
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.