Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

ios - How to efficiently find CGRects for visible words in UITextView?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...