2010-11-03 52 views
40

我有一个UILabel,但我怎样才能让用户选择它的一部分文本。我不希望用户能够编辑文本,也不希望标签/文本框具有边框。允许用户从UILabel中选择文本来复制

+0

使用https: //github.com/hoteltonight/HTCopyableLabel – 2014-05-12 14:50:41

回答

47

这是不可能与UILabel

您应该使用UITextField。只需使用textFieldShouldBeginEditing委托方法停用编辑。

+0

但是,这将有3D边界不是吗? – 2010-11-03 20:01:25

+1

几周前我用过了UITextField,我记得没有边框(它是在xib中创建的)。如果你的UITextField有一个边框,那么只需阅读文档以找出如何禁用边框。 – Yuras 2010-11-03 20:06:56

+3

http://developer.apple.com/library/ios/#documentation/uikit/reference/UITextField_Class/Reference/UITextField.html [textField setBorderStyle:UITextBorderStyleNone] – Yuras 2010-11-03 20:08:06

21

您可以使用创建UITextView并将其.editable设置为NO。然后你有一个文本视图,其中(1)用户不能编辑(2)没有边界,(3)用户可以从中选择文本。

19

一个穷人的复制和粘贴版本,如果你不能,或不需要使用文本视图,将添加一个手势识别器到标签,然后只是将整个文本复制到粘贴板。除非你使用UITextView

请确保你让用户知道它已被复制,并且你同时支持单击操作和长按操作,因为它会让用户尝试突出显示部分文字。这是一个有点示例代码,让你开始:

注册您的标签上的手势识别器,当你创建:

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textTapped:)]; 
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(textPressed:)]; 
       [myLabel addGestureRecognizer:tap]; 
       [myLabel addGestureRecognizer:longPress]; 
       [myLabel setUserInteractionEnabled:YES]; 

接下来处理手势:

- (void) textPressed:(UILongPressGestureRecognizer *) gestureRecognizer { 
    if (gestureRecognizer.state == UIGestureRecognizerStateRecognized && 
     [gestureRecognizer.view isKindOfClass:[UILabel class]]) { 
     UILabel *someLabel = (UILabel *)gestureRecognizer.view; 
     UIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; 
     [pasteboard setString:someLabel.text]; 
     ... 
     //let the user know you copied the text to the pasteboard and they can no paste it somewhere else 
     ... 
    } 
} 

- (void) textTapped:(UITapGestureRecognizer *) gestureRecognizer { 
    if (gestureRecognizer.state == UIGestureRecognizerStateRecognized && 
     [gestureRecognizer.view isKindOfClass:[UILabel class]]) { 
      UILabel *someLabel = (UILabel *)gestureRecognizer.view; 
      UIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; 
      [pasteboard setString:someLabel.text]; 
      ... 
      //let the user know you copied the text to the pasteboard and they can no paste it somewhere else 
      ... 
    } 
} 
+2

不错的答案,但你应该添加一行代码:myLabel.userInteractionEnabled = YES; – Ilario 2016-03-08 09:45:32