How to implement context menus for cut/copy/paste in a UICollectionView

Screen Shot 2015-02-03 at 11.56.47

By default a collection view cell is implementing a long press gesture recogniser. If activated the cell will bring up the familiar context menu for cut, copy and paste. It’s up to us to enable it, and it’s also up to us how to react to this menu. Here’s how we can do that.

The following three methods are provided as commented stubs in the CollectionViewController template.

Showing the Menu

First we need to tell our class that the menu is to be shown:

Returning YES here will show the menu for every cell, but since we also get an indexPath, we could make decisions based on which cell has been tapped and make the menu show up conditionally.

Next we need to decide which items we want to show:

Returning YES here will show cut, copy and paste. We can make this conditional too, based both in the indexPath for each cell, but also based on the action parameter. Here’s a variation which will only show cut and paste, but not copy:

Menu Actions

It’s up to us what happens when either of those menu items is selected by the user. We can either use the UIPasteboard to retrieve and store our values, or create a property and store out entire object in it. I only have an NSString value per cell and will use the UIPasteboard.

This method is called when the user taps a menu item:

It looks more complex than it really is: we first procure the value of our cell, and then add it to (or remove it from) the underlying data source. Typically it’s a mutable array or Core Data. Once the data is updated, we ask the collection view to reload its data which then makes the changes appear.

That’s it!

About Jay Versluis

Jay is a medical miracle known as Super Survivor. He runs two YouTube channels, five websites and several podcast feeds. To see what else he's up to, and to support him on his mission to make the world a better place, check out his Patreon Campaign.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.