Enable copy and paste on UITextField without making it editable

mrueg picture mrueg · Dec 17, 2009 · Viewed 22.2k times · Source

I want the text in a UITextField (or ideally, a UILabel) to be non-editable, but at the same time give the user the ability to copy it to paste elsewhere.

Answer

mrueg picture mrueg · Jan 30, 2010

My final solution was the following:

I created a subclass of UILabel (UITextField should work the same) that displays a UIMenuController after being tapped. CopyableLabel.m looks like this:

@implementation CopyableLabel


- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
if(action == @selector(copy:)) {
    return YES;
}
else {
    return [super canPerformAction:action withSender:sender];
}
}


- (BOOL)canBecomeFirstResponder {
return YES;
}


- (BOOL)becomeFirstResponder {
if([super becomeFirstResponder]) {
    self.highlighted = YES;
    return YES;
}
return NO;
}


- (void)copy:(id)sender {
UIPasteboard *board = [UIPasteboard generalPasteboard];
[board setString:self.text];
self.highlighted = NO;
[self resignFirstResponder];
}


- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
if([self isFirstResponder]) {
    self.highlighted = NO;
    UIMenuController *menu = [UIMenuController sharedMenuController];
    [menu setMenuVisible:NO animated:YES];
    [menu update];
    [self resignFirstResponder];
}
else if([self becomeFirstResponder]) {
    UIMenuController *menu = [UIMenuController sharedMenuController];
    [menu setTargetRect:self.bounds inView:self];
    [menu setMenuVisible:YES animated:YES];
}
}


@end