Milo Milo - 4 months ago 132
iOS Question

Convert selectedTextRange UITextRange to NSRange

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

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);
}