Iphone 允许用户从UILabel中选择要复制的文本

Iphone 允许用户从UILabel中选择要复制的文本,iphone,objective-c,uilabel,Iphone,Objective C,Uilabel,我有一个UILabel,但是如何允许用户选择它的文本的一部分呢。我不希望用户能够编辑文本,也不希望标签/文本字段有边框 使用UILabel是不可能的 为此,您应该使用UITextView。只需使用textfield shouldBeginediting委托方法禁用编辑即可。您可以使用创建UITextView并将其可编辑设置为否。这样您就有了一个文本视图,其中(1)用户无法编辑(2)没有边框,(3)用户可以从中选择文本。一个穷人版本的复制和粘贴,如果您不能,或者不需要使用文本视图,可以在标签上添加

我有一个UILabel,但是如何允许用户选择它的文本的一部分呢。我不希望用户能够编辑文本,也不希望标签/文本字段有边框

使用
UILabel
是不可能的


为此,您应该使用
UITextView
。只需使用
textfield shouldBeginediting
委托方法禁用编辑即可。

您可以使用创建UITextView并将其
可编辑
设置为否。这样您就有了一个文本视图,其中(1)用户无法编辑(2)没有边框,(3)用户可以从中选择文本。

一个穷人版本的复制和粘贴,如果您不能,或者不需要使用文本视图,可以在标签上添加手势识别器,然后将整个文本复制到粘贴板上。除非使用
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
            ...
    }
}

几周前我使用了UITextField,我记得没有边框(它是在xib中创建的)。如果UITextField有边框,请阅读文档了解如何禁用边框。你是说UITextView不是UITextField,对吗?UITextField上没有可编辑的属性。这里有一个类别可以做到这一点:实际上,任何
UIResponder
子类都可以。使用“在此处查看我的答案”或..回答不错,但您应该添加一行代码:myLabel.userInteractionEnabled=YES;