Append to NSTextView and scroll

Dr.Kameleon picture Dr.Kameleon · Mar 2, 2013 · Viewed 13.7k times · Source

OK, what I need should have been very simple. However, I've looked everywhere and I'm not sure I've found something that works 100% (and it's something that has troubled me in the past too).

So, here we are :

  • I want to be able to append to an NSTextView
  • After appending, the NSTextView should scroll down (so that that latest appended contents are visible)

Rather straightforward, huh?

So... any ideas? (A code example that performs exactly this simple "trick" would be more than ideal...)

Answer

Dr.Kameleon picture Dr.Kameleon · Mar 2, 2013

After cross-referencing several answers and sources (with some tweaks), here's the answer that does work (given _myTextView is an NSTextView outlet) :

- (void)appendToMyTextView:(NSString*)text
{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSAttributedString* attr = [[NSAttributedString alloc] initWithString:text];

        [[_myTextView textStorage] appendAttributedString:attr];
        [_myTextView scrollRangeToVisible:NSMakeRange([[_myTextView string] length], 0)];
    });
}