将NSTextView滚动到底部 [英] Scrolling NSTextView to bottom

查看:1438
本文介绍了将NSTextView滚动到底部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

每当我需要记录时我通过这种方式将新消息附加到NSTextView的文本:

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];
    }
}


$ b $ p此后,我想要NSTextField我应该说包含它的NSClipView)向下滚动以显示其文本的最后一行(显然它应该滚动,如果最后一行是不可见的,事实上如果那么新行是第一行我日志它已经在屏幕上,所以没有必要向下滚动)。

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

如何以编程方式做?

推荐答案

- (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)];
}

这篇关于将NSTextView滚动到底部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆