Allow user to select text from UILabel to copy [duplicate]
I have a UILabel, but how can I allow the user to select a portion of it's text. I don't want the user to be able to edit the text nor the label/textfield to have a border.
It is not possible with UILabel
.
You should use UITextView
for that. Just disable editing using textFieldShouldBeginEditing
delegate method.
You use create a UITextView and make its .editable
to NO. Then you have a text view which (1) the user cannot edit (2) have no border and (3) the user can select text from it.
A poor man's version of copy and paste, if you cannot, or don't need to use a text view, would be to add a gesture recognizer to the label and then just copy the entire text to the pasteboard. It's not possible to do just a portion unless you use a UITextView
Make sure you let the user know it's been copied and that you support both a single tap gesture as well as a long press, as it will pick up users trying to highlight a portion of text. Here is a bit of sample code to get you started:
Register the gesture recognizers on your label when you create it:
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];
Next up handle the gestures:
- (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
...
}
}