swiftuitextviewnsrangeselectedtext

How to select a text in a textView having a NSRange in Swift?


I have a UITextView where I would like to select a part of the text. I'm trying to use selectedTextRange, unfortunately I get this error:

Cannot convert value of type 'NSRange' (aka '_NSRange') to expected argument type 'UITextRange'

This is the code I'm trying to use:

mainTextField.becomeFirstResponder()
mainTextField.selectedTextRange = mainTextField.textInRange(matchRange) // matchRange is a NSRange

The range I'm using is coming from a Regex which I adapted from this tutorial1:

EDIT: added the first line

if let regex =  NSRegularExpression(options: searchOptions){ // refers to an installed extension convenience init
let range = NSMakeRange(0, (mainTextField.text.characters.count))
let matches = regex.matchesInString(mainTextField.text, options: [], range: range)
[...]

Solution

  • You can add an extension on UITextView that will do the conversion.

        extension UITextView
        {
            func textRangeFromNSRange(range:NSRange) -> UITextRange?
            {
                let beginning = self.beginningOfDocument
                guard let start = self.positionFromPosition(beginning, offset: range.location), end = self.positionFromPosition(start, offset: range.length) else { return nil}
    
                return self.textRangeFromPosition(start, toPosition: end)
            }
        }
    

    Use

        if let range = mainTextView.textRangeFromNSRange(range: matchRange){
            mainTextField.selectedTextRange = range
        }
    

    Where matchRange is an NSRange and range is a UITextRange