Enable copy and paste on UITextField without making it editable

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 and paste it.

-------------Problems Reply------------

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

Try UITextView instead (I suspect it would work like a UILabel for you). I tested this with its editable property set to NO, and double-tapping-to-copy worked for me.

Another solution is keeping the UITextField enabled but programmatically preventing it from being edited. This is done with the following delegate method:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
return NO;
}

I'm not aware of possible limitations though, currently suits my needs.

Category:ios Views:0 Time:2009-12-17

Related post

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.163 (s). 11 q(s)