0

I have this UITextView that is updated in a loop. Text is appended to the end of the text view at every loop. The textview updates but does not scroll to show the end of the text view.

The method I use to append the text is:

- (void)appendText:(NSString*)text toTextView:(UITextView *)textView
{
  dispatch_async(dispatch_get_main_queue(), ^{
    NSAttributedString* attr = [[NSAttributedString alloc] initWithString:text];
    [[textView textStorage] appendAttributedString:attr];
    [textView scrollRangeToVisible:NSMakeRange([[textView text] length], 0)];
    [textView setNeedsDisplay];
    [textView setNeedsLayout];
  });
}

The textview updates with text but continues to show just the top.

this is compiled for iOS 7+ only.

Other answers on SO are not solving this.

any clues?

Mahboob Nur
  • 739
  • 2
  • 9
  • 34
Duck
  • 34,902
  • 47
  • 248
  • 470

2 Answers2

1

You might want to see this: https://github.com/steipete/PSPDFTextView

Basically, you need to give UITextView some time to do the calculation. Don't scroll immediately, wait for a few moments (~0.2sec) before trying to scroll the text view. And, avoid having blank line at the end of text. You needed to add at least one character in the last line. (Space works for me)

Bird
  • 1,129
  • 7
  • 10
1

Did this solution not work? (Not knowing how your loop was implemented, I was unable to replicate the misbehavior; firing your method from an NSTimer worked fine for me.)

Essentially, disable scrolling on your UITextView immediately before calling scrollRangeToVisible:, and re-enable scrolling immediately after:

- (void)appendText:(NSString*)text toTextView:(UITextView *)textView
{
  dispatch_async(dispatch_get_main_queue(), ^{
    NSAttributedString* attr = [[NSAttributedString alloc] initWithString:text];
    [[textView textStorage] appendAttributedString:attr];
    textView.scrollEnabled = NO;
    [textView scrollRangeToVisible:NSMakeRange([[textView text] length], 0)];
    textView.scrollEnabled = YES;
    [textView setNeedsDisplay];
    [textView setNeedsLayout];
  });
}
Community
  • 1
  • 1
Peter Heide
  • 519
  • 4
  • 13
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – Iwillnotexist Idonotexist Aug 31 '14 at 19:08
  • @iwillnotexist-idonotexist I've edited my answer to include a description of the solution. Thanks for the suggestion. – Peter Heide Aug 31 '14 at 21:01
  • To a certain extent I shouldn't be thanked; The text of my comment is actually a canned response available to reviewers with at least 500 or 2000 rep (Not sure exactly) going through reviews of questions that have been flagged one way or another. But it looks like the response's "niceness" has been validated. Anyways, +1. – Iwillnotexist Idonotexist Aug 31 '14 at 22:00