在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 and paste it.
推荐答案
我的最终解决方案是可编辑的,但同时给予用户复制和粘贴它的能力。是以下:
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屋!
查看全文