gpt4 book ai didi

macos - 将 NSTextView 滚动到底部

转载 作者:行者123 更新时间:2023-12-03 16:03:54 29 4
gpt4 key购买 nike

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

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

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

在此之后,我希望 NSTextField (或者也许我应该说包含它的 NSClipView )向下滚动以显示其文本的最后一行(显然,仅当最后一行尚不可见时才应该滚动,在事实上,如果新行是我记录的第一行,它已经在屏幕上,所以不需要向下滚动)。

我怎样才能以编程方式做到这一点?

最佳答案

找到解决方案:

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

关于macos - 将 NSTextView 滚动到底部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15546808/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com