Bryan Chen Bryan Chen - 1 year ago 241
iOS Question

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

to scroll the text view

Answer Source

The way i would do it is to compute all the sizes of each paragraph. With sizeWithFont:constrainedToSize:lineBreakMode:

you will then be able to work out which paragraph is visible, from the [textView contentOffset].

to scroll, dont use scrollRangeToVisible, just use setContentOffset: The CGPoint y parameter for this should either be the sum of all the height sizes to the next paragraph, or just add the textView.frame.size.height, if that is closer than the beginning of the next paragraph.

This make sense?

in answer to comment requst code bellow (untested):

  CGFloat paragraphOffset[MAX_PARAGRAPHS];

    CGSize constraint = CGSizeMake(widthOfTextView, 999999 /*arbitrarily large number*/);
    NSInteger paragraphNo = 0;
    CGFloat offset = 0;

    for (NSString* paragraph in paragraphs) {
        paragraphOffset[paragraphNo++] = offset;
        CGSize paragraphSize = [paragraph sizeWithFont:textView.font constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
        offset += paragraphSize.height;

    // find visible paragraph
    NSInteger visibleParagraph = 0;
    while (paragraphOffset[visibleParagraph++] < textView.contentOffset.y);

    // scroll to paragraph 6
    [textView setContentOffset:CGPointMake(0, paragraphOffset[6]) animated:YES];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download