在 UITextField 上启用复制和粘贴而不使其可编辑 [英] Enable copy and paste on UITextField without making it editable
本文介绍了在 UITextField 上启用复制和粘贴而不使其可编辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望 UITextField
(或理想情况下,UILabel
)中的文本不可编辑,但同时给出用户可以将其复制粘贴到其他地方.
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:
我创建了一个 UILabel 的子类(UITextField 应该工作相同),它在被点击后显示一个 UIMenuController.CopyableLabel.m 看起来像这样:
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
这篇关于在 UITextField 上启用复制和粘贴而不使其可编辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文