代码之家  ›  专栏  ›  技术社区  ›  Jonathan.

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

  •  49
  • Jonathan.  · 技术社区  · 14 年前

    3 回复  |  直到 14 年前
        1
  •  60
  •   Yuras    8 年前

    这是不可能的 UILabel

    你应该用 UITextField 为了这个。只是禁用编辑使用 textFieldShouldBeginEditing 委托方法。

        2
  •  32
  •   kennytm    14 年前

    使用create a UITextView并使其 .editable

        3
  •  24
  •   theDuncs    7 年前

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