BDGapps BDGapps - 2 years ago 189
iOS Question

UITextPosition to NSRange

I need to use NSStringFromRange but I only have a start and end UITextPositions. How do you convert UITextPosition to 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;

Answer Source

Try this:

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)];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download