3.10. Displaying Context Menus on Table Views Cells

Problem

You want to give your users the ability to use copy/paste options among other operations that they can choose, by holding down one of their fingers on a table view cell in your app.

Solution

Implement the following three methods of the UITableViewDelegate protocol in the delegate object of your table view:

tableView:shouldShowMenuForRowAtIndexPath:

The return value of this method is of type BOOL. If you return YES from this method, iOS will display the context menu for the table view cell whose index gets passed to you through the shouldShowMenuForRowAtIndexPath parameter.

tableView:canPerformAction:forRowAtIndexPath:withSender:

The return value of this method is also of type BOOL. Once you allow iOS to display context menu for a table view cell, iOS will call this method multiple times and pass you the selector of the action that you can choose to display in the context menu or not. So if iOS wants to ask you whether you would like to show the Copy menu to be displayed to the user, this method will get called in your table view’s delegate object and the canPerformAction parameter of this method will be equal to @selector(copy:). We will read more information about this in this recipe’s Discussion.

tableView:performAction:forRowAtIndexPath:withSender:

Once you allow a certain action to be displayed in the context menu of a table view cell, when the user picks that action from the menu, this method will get called in your table view’s ...

Get iOS 5 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.