Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scrolling NSTextView to bottom

I'm making a little server app for OS X and I'm using an NSTextView to log some info about connected clients.

Whenever I need to log something I'm appending the new message to the text of the NSTextView this way:

- (void)logMessage:(NSString *)message
{
    if (message) {
        self.textView.string = [self.textView.string stringByAppendingFormat:@"%@\n",message];
    }
}

After this I'd like the NSTextField (or maybe I should say the NSClipView that contains it) to scroll down to show the last line of its text (obviously it should scroll only if the last line is not visible yet, in fact if then new line is the first line I log it is already on the screen so there is no need to scroll down).

How can I do that programmatically?

like image 463
BigLex Avatar asked Mar 21 '13 11:03

BigLex


Video Answer


2 Answers

As of OS 10.6 it's as simple as nsTextView.scrollToEndOfDocument(self).

like image 33
kellanburket Avatar answered Sep 28 '22 00:09

kellanburket


Found solution:

- (void)logMessage:(NSString *)message
{
    if (message) {
        [self appendMessage:message];
    }
}

- (void)appendMessage:(NSString *)message
{
    NSString *messageWithNewLine = [message stringByAppendingString:@"\n"];

    // Smart Scrolling
    BOOL scroll = (NSMaxY(self.textView.visibleRect) == NSMaxY(self.textView.bounds));

    // Append string to textview
    [self.textView.textStorage appendAttributedString:[[NSAttributedString alloc]initWithString:messageWithNewLine]];

    if (scroll) // Scroll to end of the textview contents
        [self.textView scrollRangeToVisible: NSMakeRange(self.textView.string.length, 0)];
}
like image 163
BigLex Avatar answered Sep 27 '22 22:09

BigLex