Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable copy and paste on UITextField without making it editable

Tags:

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.

like image 559
mrueg Avatar asked Dec 17 '09 09:12

mrueg


1 Answers

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 
like image 74
mrueg Avatar answered Oct 01 '22 18:10

mrueg