附加到 NSTextView [英] Appending to NSTextView
问题描述
我有一个 NSTask
(设置了一个 NSPipe
)在后台运行,我想在它们进来时输出内容一个 NSTextView
(output
).
I've got an NSTask
(with an NSPipe
set up) running in the background and I want to output the contents, as they're coming in, in an NSTextView
(output
).
我使用的代码是:
NSMutableAttributedString* str = [[NSMutableAttributedString alloc] initWithString:s];
//[str addAttribute:NSForegroundColorAttributeName value:[NSColor whiteColor] range:NSMakeRange(0, [str length])];
[[output textStorage] appendAttributedString:str];
[output scrollRangeToVisible:NSMakeRange([[output string] length], 0)];
<小时>
问题:
- 当有大量数据附加时,视图看起来像闪烁"...并且无法正常工作.
- 鉴于
NSTextView
位于工作表上,当鼠标指针在其他地方而不是悬停在NSTextView
上方时,似乎没有任何内容出现 - 为什么会这样,虽然我已经设置了
NSTextView
的颜色/插入颜色/etc,但这似乎不适用于新插入的文本? - 在
NSTextView
上附加(+滚动) 的建议的方法是什么?
- When there is a lot of data appending, the view seems like "flashing"... and not working properly.
- Given that the
NSTextView
is on a Sheet, NO CONTENTS seem to be appearing when the mouse pointer is elsewhere other than hovering above theNSTextView
- Why is that, although I've set the color/insertion color/etc of the
NSTextView
, this doesn't seem to apply to newly inserted text? - What's the suggested way of appending (+scrolling) on an
NSTextView
?
谢谢!
推荐答案
请记住,用户界面元素(包括 NSTextView
)在主线程上发挥作用.如果您尝试向文本视图添加信息,那么您最好这样做.方法如下:
Remember that user interface elements, and this includes NSTextView
, do their magic on the main thread. If you're attempting to add information to the text view, that's where you'd best be doing it. Here's how:
[[output textStorage] performSelectorOnMainThread:@selector(appendAttributedString:)
withObject:str
waitUntilDone:YES];
我想解决你的第三点,但坦率地说,我仍然是一个学生.
I'd address your third point, but frankly, that's a thing of which I'm still very much a student.
为了解决您的第四点,您似乎已经弄清楚了;只需结合您的追加和滚动操作.但就像更改 textStorage
的内容一样,您需要确保在主线程上执行此操作.由于 -scrollRangeToVisible:
不接受对象作为其参数,因此您必须以不同的方式执行此操作:
To address your fourth point, it would appear you've got that figured out; just combine your append and scroll actions. But just like changing the contents of textStorage
, you want to be sure you're doing this on the main thread. Since -scrollRangeToVisible:
doesn't take an object for its argument, you have to do this a bit differently:
dispatch_async(dispatch_get_main_queue(), ^{
[output scrollRangeToVisible:NSMakeRange([[output string] length], 0)];
});
尽管是我的第一个示例,您也可以在该块内调用 -appendAttributedString:
:
My first example notwithstanding, you could place your call to -appendAttributedString:
inside that block as well:
dispatch_async(dispatch_get_main_queue(), ^{
[[output textStorage] appendAttributedString:str];
[output scrollRangeToVisible:NSMakeRange([[output string] length], 0)];
});
这篇关于附加到 NSTextView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!