Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 746
Milo Avatar asked Jan 15 '14 22:01

Milo


4 Answers

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); } 
like image 152
Vitaly S. Avatar answered Oct 20 '22 15:10

Vitaly S.


Here's a Swift extension based on the answer by Vitaly S.

extension UITextInput {     var selectedRange: NSRange? {         guard let range = self.selectedTextRange else { return nil }         let location = offsetFromPosition(beginningOfDocument, toPosition: range.start)         let length = offsetFromPosition(range.start, toPosition: range.end)         return NSRange(location: location, length: length)     } } 

Swift 4

extension UITextInput {     var selectedRange: NSRange? {         guard let range = selectedTextRange else { return nil }         let location = offset(from: beginningOfDocument, to: range.start)         let length = offset(from: range.start, to: range.end)         return NSRange(location: location, length: length)     } } 
like image 34
Daniel Wood Avatar answered Oct 20 '22 15:10

Daniel Wood


UITextView has a property

@property(nonatomic) NSRange selectedRange;
like image 36
yasirmturk Avatar answered Oct 20 '22 15:10

yasirmturk


Swift 5

extension UITextInput
{
    var selectedRange: NSRange?
    {
        if let selectedRange = self.selectedTextRange
        {
           return NSMakeRange(self.offset(from: self.beginningOfDocument, to: selectedRange.start),
                              self.offset(from: selectedRange.start,      to: selectedRange.end))
        }
        else
        {
            return nil
        }
    }
}
like image 26
Leslie Godwin Avatar answered Oct 20 '22 16:10

Leslie Godwin