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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With