我需要使用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; }
解决方法
尝试这个:
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)];