我有一个UILabel,但是如何让用户选择它的一部分文本。我不希望用户能够编辑文本,也不希望标签/文本字段具有边框。
答案 0 :(得分:56)
UILabel
无法实现。
您应该使用UITextField
。只需使用textFieldShouldBeginEditing
委托方法禁用编辑。
答案 1 :(得分:26)
您使用创建UITextView并使其.editable
为NO。然后你有一个文本视图,(1)用户无法编辑(2)没有边框,(3)用户可以从中选择文字。
答案 2 :(得分:22)
一个穷人的复制和粘贴版本,如果你不能,或者不需要使用文本视图,那就是在标签上添加一个手势识别器,然后只复制整个文本到了纸板。除非您使用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
...
}
}