Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ios - how to find what is the visible range of text in UITextView?

how to find what text is visible in a scrollable, non-ediable UITextView?

for example i may need to show next paragraph, then i want to find the current visible text range and use it to calculate the appropriate range and use scrollRangeToVisible: to scroll the text view

like image 336
Bryan Chen Avatar asked May 20 '11 05:05

Bryan Chen


1 Answers

I find another solution here. It's a better way to solve this problem in my eyes. https://stackoverflow.com/a/9283311/889892

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 152
Senry Avatar answered Oct 29 '22 23:10

Senry