Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append to NSTextView and scroll

Tags:

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

like image 817
Dr.Kameleon Avatar asked Mar 02 '13 09:03

Dr.Kameleon


2 Answers

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)];     }); } 
like image 186
Dr.Kameleon Avatar answered Sep 19 '22 11:09

Dr.Kameleon


The appendAttributedString and scrollToEndOfDocument are available starting in OS X 10.0 and 10.6 respectively

extension NSTextView {     func append(string: String) {         self.textStorage?.appendAttributedString(NSAttributedString(string: string))         self.scrollToEndOfDocument(nil)     } } 
like image 43
neoneye Avatar answered Sep 19 '22 11:09

neoneye