Convert selectedTextRange UITextRange to NSRange

Milo picture Milo · Jan 15, 2014 · Viewed 16.7k times · Source

How can I convert a UITextRange object to an NSRange? I've seen plenty of SO posts about going the other direction but that's the opposite of what I need. I'm using the UITextRange selectedTextRange which is a property of a UITextView. It returns a UITextRange but I need a range.

Answer

Vitaly S. picture Vitaly S. · Jan 15, 2014

You need something like this:

- (NSRange) selectedRangeInTextView:(UITextView*)textView
{
    UITextPosition* beginning = textView.beginningOfDocument;

    UITextRange* selectedRange = textView.selectedTextRange;
    UITextPosition* selectionStart = selectedRange.start;
    UITextPosition* selectionEnd = selectedRange.end;

    const NSInteger location = [textView offsetFromPosition:beginning toPosition:selectionStart];
    const NSInteger length = [textView offsetFromPosition:selectionStart toPosition:selectionEnd];

    return NSMakeRange(location, length);
}