简体   繁体   English

在UITextView中获取选定的文本

[英]Get selected text in a UITextView

I have a UITextView , and I want to allow the user to highlight a portion of text and copy it with a button instead of using the default Apple method. 我有一个UITextView ,我希望允许用户突出显示一部分文本并使用按钮复制它,而不是使用默认的Apple方法。 The problem is that I can't get the text within the selected range. 问题是我无法在所选范围内获得文本。

Here's what I have: 这是我所拥有的:

@IBAction func copyButton(_ sender: Any) {
    let selectedRange: UITextRange? = textView.selectedTextRange
    selectedText = textView.textInRange(selectedRange)
    UIPasteboard.general.string = selectedText
}

But I'm getting 但是我越来越

UITextView has no member textInRange UITextView没有成员textInRange

and I'm not sure what I should be using instead. 而且我不确定应该使用什么。

What is happening is that UITextView method textInRange have been renamed to text(in: Range) since Swift 3. Btw you forgot to add the let keyword in your sentence: 发生的事情是,自Swift 3起, UITextView方法textInRange已重命名为text(in: Range) 。顺便说一句,您忘了在句子中添加let关键字:

if let range = textView.selectedTextRange {
    UIPasteboard.general.string = textView.text(in: range)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM