将NSTextView滚动到底部

Big*_*Lex 10 macos cocoa nstextview

我正在为OS X制作一个小型服务器应用程序,我正在使用NSTextView来记录有关已连接客户端的一些信息.

每当我需要记录某些东西时,我就会以这种方式将新消息附加到NSTextView的文本中:

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

在此之后我想要NSTextField(或者我应该说包含它的NSClipView)向下滚动以显示其文本的最后一行(显然它应该只在最后一行不可见时滚动,事实上如果那么新行是我记录的第一行,它已经在屏幕上,因此无需向下滚动).

我该如何以编程方式执行此操作?

Big*_*Lex 15

找到解决方案

- (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)];
}
Run Code Online (Sandbox Code Playgroud)


kel*_*ket 9

从OS 10.6开始,就像它一样简单nsTextView.scrollToEndOfDocument(self).

  • 谢谢!你也可以传递 nil,而不是 self。 (2认同)

scu*_*cum 6

斯威夫特 4 + 5

let smartScroll = self.textView.visibleRect.maxY == self.textView.bounds.maxY

self.textView.textStorage?.append("new text")

if smartScroll{
    self.textView.scrollToEndOfDocument(self)
}

Run Code Online (Sandbox Code Playgroud)