Enabling the copy menu on a UITableViewCell

I’d been testing out building master/detail table views using Core Data as a source, and realized it would be great if I could select the table cells in my detail view to copy the contents. It takes just additional three methods in the UITableViewDelegate.

First, we say that the menu should appear on a long press. In my case, I only wanted the first two sections to have the copy menu appear, so I check indexPath.section:

- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath {
    return (indexPath.section < 2);
}

Next, we indicate which actions we want to handle. These cells aren’t editable, so I only wanted to allow the user to copy the text:

- (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
    return (action == @selector(copy:));
}

Lastly, we handle the actual action — in my case, the copy action. To do so, I first retrieve the cell at the requested indexPath, then assign the detailTextLabel’s text to the pasteboard.

- (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
    if (action == @selector(copy:)) {
        UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
        [[UIPasteboard generalPasteboard] setString:cell.detailTextLabel.text];
    }
}

For more information, check out the methods in the UITableViewDelegate documentation.

Tagged ,

Leave a comment