将selectedTextRange UITextRange转换为NSRange

时间:2014-01-15 22:38:42

标签: ios objective-c nsrange uitextrange

如何将UITextRange对象转换为NSRange?我已经看到很多关于走向另一个方向的SO帖子,但这与我需要的相反。我使用的UITextRange selectedTextRangeUITextView的属性。它返回UITextRange,但我需要一个范围。

4 个答案:

答案 0 :(得分:48)

你需要这样的东西:

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

答案 1 :(得分:9)

这是基于Vitaly S答案的Swift扩展。

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

答案 2 :(得分:8)

UITextView有一个属性

@property(nonatomic) NSRange selectedRange;

答案 3 :(得分:0)

快捷键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
        }
    }
}