How to get the rects from UITextRange in earlier iOS version than iOS 6.0

780 Views Asked by At

I wanna get the all rects from UITextRange. you know, if UITextView line wrap, the UITextRange will be represented by more than 1 CGRect. in iOS 6.0, there is a method as "selectionRectsForRange:", so you can get the all CGRects. But in older version, there is only a method "firstRectForRange:" I checked the APIs documents again and again, but i find nothing.

My code likes blow:

UITextPosition *beginning = textView.beginningOfDocument;
UITextPosition *start = [textView positionFromPosition:beginning offset:range.location];
UITextPosition *end = [textView positionFromPosition:start offset:range.length];
UITextRange *textRange = [textView textRangeFromPosition:start toPosition:end];

//(in iOS 6.0)      
NSArray *array = [textView selectionRectsForRange:textRange];
for (int i=0; i<[array count]; i++) {
    NSLog(@"rect array = %@", NSStringFromCGRect([[array objectAtIndex:i] rect]));
}
// (in earlier version)
CGRect rect = [textView firstRectForRange:textRange];
2

There are 2 best solutions below

0
On

Based on the information in this answer: How to find position or get rect of any word in textview and place buttons over that?

You have to call firstRectForRange repeatedly.

When you get the first rect back you'll be able to check its range. Using this and the range you supplied originally, you can call firstRectForRange again with an adjusted range (if needed)...

0
On

How about using frameOfTextRange and then do something like this . But I'am not sure if this works with your specific iOS version.

- (CGRect)frameOfTextRange:(NSRange)range inTextView:(UITextView *)textView
{
    UITextPosition *beginning = textView.beginningOfDocument;
    UITextPosition *start = [textView positionFromPosition:beginning offset:range.location];
    UITextPosition *end = [textView positionFromPosition:start offset:range.length];
    UITextRange *textRange = [textView textRangeFromPosition:start toPosition:end]];
    CGRect rect = [textView firstRectForRange:textRange];
    return [textView convertRect:rect fromView:textView.textInputView];
}