Josh
Josh

Reputation: 25

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. 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

and I'm not sure what I should be using instead.

Upvotes: 1

Views: 2076

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236538

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:

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

Upvotes: 3

Related Questions