1

How to do to get the selected string from a NSTextView in Swift?

// create a range of selected text let range = mainTextField.selectedRange() // this works but I need a plain string not an attributed string let str = mainTextField.textStorage?.attributedSubstring(from: range) 

Maybe I have to add an intermediate step where I get the full string and then apply the range on it?

2

3 Answers 3

5

What about

let str = mainTextField.text.substring(with: range) 

Edit:

This should work now:

let range = mainTextField.selectedRange() // Returns NSRange :-/ (instead of Range) let str = mainTextField.string as NSString? // So we cast String? to NSString? let substr = str?.substring(with: range) // To be able to use the range in substring(with:) 
Sign up to request clarification or add additional context in comments.

2 Comments

But this won't work when there are emojis in UITextView. I got error at this line mainEditor.textStorage.string[range.lowerBound - 1]). Caused by Can't advance past endIndex. mainEditor.textStorage.string print 322, range.lowerBound - 1 print 323.
I can't see how the code in your comment refers to the answer.
1

The code snippet in the Swift 5. That's not very hard but repeated

let string = textView.attributedString().string let selectedRange = textView.selectedRange() let startIndex = string.index(string.startIndex, offsetBy: selectedRange.lowerBound) let endIndex = string.index(string.startIndex, offsetBy: selectedRange.upperBound) let substring = textView.attributedString().string[startIndex..<endIndex] let selectedString = String(substring) 

Comments

0

In case anyone is having issues with the selectedRanges() not returning the proper range for an NSTextView, make sure that you have made your NSTextView selectable. I don't know if it's not selectable by default but I had to enable it;
textView.isSelectable = true
I was trying this in Swift 5 using @user25917 code sample above and I couldn't get the ranges no matter what. I was getting a visual confirmation the text was selected through highlighting which threw me off. This was driving me mad for a few hours.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.