18

我需要使用 NSStringFromRange 但我只有一个开始和结束 UITextPositions。如何将 UITextPosition 转换为 NSRange。

NSMutableArray * wordArray = [[NSMutableArray alloc]init];
id<UITextInputTokenizer> tokenizer = tv.tokenizer;
UITextPosition *start = tv.beginningOfDocument;
while (![start isEqual:tv.endOfDocument]) {
    UITextPosition *end = [tokenizer positionFromPosition:start toBoundary:UITextGranularityWord inDirection:UITextStorageDirectionForward];
    NSString *word = [tv textInRange:[tv textRangeFromPosition:start toPosition:end]];
    [wordArray addObject:NSStringFromRange(<#NSRange range#>)];
    start = end;
}
4

4 回答 4

24

尝试这个:

NSInteger startOffset = [tv offsetFromPosition:tv.beginningOfDocument toPosition:start];
NSInteger endOffset = [tv offsetFromPosition:tv.beginningOfDocument toPosition:end];
NSRange offsetRange = NSMakeRange(startOffset, endOffset - startOffset);
[wordArray addObject:NSStringFromRange(offsetRange)];
于 2012-07-31T03:40:54.050 回答
8
- (NSRange)rangeFromTextRange:(UITextRange *)textRange inTextView:(UITextView*)textView {

    UITextPosition* beginning = textView.beginningOfDocument;
    UITextPosition* start = textRange.start;
    UITextPosition* end = textRange.end;

    const NSInteger location = [textView offsetFromPosition:beginning toPosition:start];
    const NSInteger length = [textView offsetFromPosition:start toPosition:end];

    return NSMakeRange(location, length);
}
于 2014-01-25T20:40:56.130 回答
4

Swift3版本

    func angeFromTextRange(textRange:UITextRange,textView:UITextView) -> NSRange {
       let location:Int = textView.offset(from: textView.beginningOfDocument, to: textRange.start)
       let length:Int = textView.offset(from: textRange.start, to: textRange.end)
       return NSMakeRange(location, length)
}
于 2017-09-03T16:28:24.267 回答
2

@Peter Lapisu 答案的Swift 2版本

方法1:作为函数

func rangeFromTextRange(textRange:UITextRange,textView:UITextView) -> NSRange {
        let location:Int = textView.offsetFromPosition(textView.beginningOfDocument, toPosition: textRange.start)
        let length:Int = textView.offsetFromPosition(textRange.start, toPosition: textRange.end)
        return NSMakeRange(location, length)
    }

方法2:作为扩展

extension UITextView {
    func rangeFromTextRange(textRange:UITextRange) -> NSRange {
        let location:Int = self.offsetFromPosition(self.beginningOfDocument, toPosition: textRange.start)
        let length:Int = self.offsetFromPosition(textRange.start, toPosition: textRange.end)
        return NSMakeRange(location, length)
    }
}
于 2016-06-05T17:26:37.290 回答