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.
A:
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.
Alex Reynolds
2009-12-17 10:49:05
I would suspect though that with the field uneditable, no paste button would appear. Let us know if that's true.
wkw
2009-12-17 14:36:35
The original question is not written clearly, then. I read "ability to copy and paste" to mean pasting it somewhere else. Reading it the other way, how can you possibly paste something into a UI widget that is *not* editable? I don't think such a widget exists.
Alex Reynolds
2009-12-17 19:49:29
+2
A:
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
mrueg
2010-01-30 14:27:22