Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to efficiently find CGRects for visible words in UITextView?

Tags:

ios

My goal is to mark all visible misspelled words in an UITextView.

The inefficient algorithm is to use the spell checker to find all ranges of misspelled words in the text, convert them to UITextRange objects using positionFromPosition:inDirection:offset etc, then get the graphics rects using the UITextInput method firstRectFromRange.

Thus all the text -> misspelled words-> NSRange collection -> UITextRange collection -> CGRect collection -> evaluate for visibility, draw visible ones

The problem is that this requires that all the text is checked, and all misspelled words are converted to graphics rects.

Thus, I imagine the way to go is to somehow find out what parts of the underlying .text in the UITextView that is visible at the moment.

Thus for range of text visible -> misspelled words-> NSRange collection -> UITextRange collection -> CGRect collection -> evaluate for visibility, draw visible ones

The code in ios - how to find what is the visible range of text in UITextView? might work as a way to bound what parts of the text to check, but still requires that all text is measured, which I imagine could be quite costly.

Any suggestions?

like image 361
Anders Sewerin Johansen Avatar asked Feb 14 '12 19:02

Anders Sewerin Johansen


1 Answers

Since UITextView is a subclass of UIScrollView, its bounds property reflects the visible part of its coordinate system. So something like this should work:

- (NSRange)visibleRangeOfTextView:(UITextView *)textView {
    CGRect bounds = textView.bounds;
    UITextPosition *start = [textView characterRangeAtPoint:bounds.origin].start;
    UITextPosition *end = [textView characterRangeAtPoint:CGPointMake(CGRectGetMaxX(bounds), CGRectGetMaxY(bounds))].end;
    return NSMakeRange([textView offsetFromPosition:textView.beginningOfDocument toPosition:start],
        [textView offsetFromPosition:start toPosition:end]);
}

This assumes a top-to-bottom, left-to-right text layout. If you want to make it work for other layout directions, you will have to work harder. :)

like image 159
rob mayoff Avatar answered Oct 04 '22 07:10

rob mayoff