Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextPosition to NSRange

Tags:

ios

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;
}
like image 768
BDGapps Avatar asked Jul 31 '12 02:07

BDGapps


2 Answers

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)];
like image 104
rob mayoff Avatar answered Oct 18 '22 20:10

rob mayoff


- (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);
}
like image 8
Peter Lapisu Avatar answered Oct 18 '22 19:10

Peter Lapisu