Convert selectedTextRange UITextRange to NSRange

后端 未结 4 1709
失恋的感觉
失恋的感觉 2020-12-24 12:56

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 wha

相关标签:
4条回答
  • 2020-12-24 13:03

    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)
        }
    }
    
    0 讨论(0)
  • 2020-12-24 13:04

    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);
    }
    
    0 讨论(0)
  • 2020-12-24 13:05

    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
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-24 13:20

    UITextView has a property

    @property(nonatomic) NSRange selectedRange;
    
    0 讨论(0)
提交回复
热议问题