Convert selectedTextRange UITextRange to NSRange
ios, nsrange, objective-c, uitextrange
Solution
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);
}
Problem
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.