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?
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. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With