2

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];
leppie
  • 115,091
  • 17
  • 196
  • 297
Oliver
  • 46
  • 5

2 Answers2

0

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)...

Community
  • 1
  • 1
Gavin Hope
  • 2,173
  • 24
  • 38
0

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];
}
Mingebag
  • 748
  • 2
  • 20
  • 35