Adding Copy Functionality to UITableView

iMessage on iPhone allows you to copy the content of a message by long pressing on a cell. This article shows you how to mimic this behaviour on iOS 5+.

Implementing such functionality used to be pretty hard (http://stackoverflow.com/questions/1146587/how-to-get-uimenucontroller-work-for-a-custom-view) but in iOS 5, all you have to do is to implement following 3 delegate methods for your UITableView.

– tableView:shouldShowMenuForRowAtIndexPath:

– tableView:canPerformAction:forRowAtIndexPath:withSender:

– tableView:performAction:forRowAtIndexPath:withSender:

Implementation of the copy functionality can look something like this.

-(void)tableView:(UITableView*)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath*)indexPath withSender:(id)sender {

    UIPasteboard* pasteboard = [UIPasteboard generalPasteboard];

    Message* message = [self.messages objectAtIndex:indexPath.row];

    pasteboard.string = message.text;
}

-(BOOL)tableView:(UITableView*)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath*)indexPath withSender:(id)sender {

    if (action == @selector(copy:)) {
        return YES;
    }

    return NO;
}

-(BOOL)tableView:(UITableView*)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath*)indexPath {
    return YES;
}

Tags: , , , , ,

Unknown's avatar

About Petr Pavlik

I'm an iOS developer currently living in Prague.

Leave a comment