允许用户从 UILabel 选择文本进行复制
我有一个 UILabel,但如何允许用户选择其文本的一部分。我不希望用户能够编辑文本,也不希望标签/文本字段具有边框。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
UILabel
不可能做到这一点。您应该使用
UITextView
来实现这一点。只需使用textFieldShouldBeginEditing
委托方法禁用编辑即可。It is not possible with
UILabel
.You should use
UITextView
for that. Just disable editing usingtextFieldShouldBeginEditing
delegate method.您使用创建一个 UITextView 并将其
.editable
设置为 NO。然后你有一个文本视图,(1)用户无法编辑(2)没有边框,(3)用户可以从中选择文本。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.如果您不能或不需要使用文本视图,复制和粘贴的穷人版本就是向标签添加手势识别器,然后将整个文本复制到粘贴板。除非您使用 UITextView,否则不可能只执行一部分。
请确保让用户知道它已被复制,并且您支持单击手势和长按手势,因为它会选择用户试图突出显示文本的一部分。下面是一些示例代码,可帮助您入门:
创建标签时在标签上注册手势识别器:
接下来处理手势:
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:
Next up handle the gestures: