【发布时间】:2011-05-17 01:29:55
【问题描述】:
我正在尝试在 NSTextView 上编写“突出显示”功能。目前,一切都很好。您选择一个文本范围,该文本的背景颜色变为黄色。但是,虽然它仍处于选中状态,但背景是所选文本的标准蓝色。如何使标准选择指示器颜色在某些情况下不显示?
谢谢!
【问题讨论】:
标签: cocoa colors highlighting highlight nstextview
我正在尝试在 NSTextView 上编写“突出显示”功能。目前,一切都很好。您选择一个文本范围,该文本的背景颜色变为黄色。但是,虽然它仍处于选中状态,但背景是所选文本的标准蓝色。如何使标准选择指示器颜色在某些情况下不显示?
谢谢!
【问题讨论】:
标签: cocoa colors highlighting highlight nstextview
使用-[NSTextView setSelectedTextAttributes:...]。
例如:
[textView setSelectedTextAttributes:
[NSDictionary dictionaryWithObjectsAndKeys:
[NSColor blackColor], NSBackgroundColorAttributeName,
[NSColor whiteColor], NSForegroundColorAttributeName,
nil]];
如果您根本不希望以任何方式指示选择(不隐藏插入点),您可以简单地传递一个空字典。
另一个选项是监视选择更改并使用temporary attributes 应用“选择”。注意临时属性用于显示拼写和语法错误并查找结果;因此,如果您关心保留 NSTextView 的这些功能,请确保仅添加和删除临时属性,而不是替换它们。
这方面的一个例子是(在 NSTextView 子类中):
- (void)setSelectedRanges:(NSArray *)ranges affinity:(NSSelectionAffinity)affinity stillSelecting:(BOOL)stillSelectingFlag;
{
NSArray *oldRanges = [self selectedRanges];
for (NSValue *v in oldRanges) {
NSRange oldRange = [v rangeValue];
if (oldRange.length > 0)
[[self layoutManager] removeTemporaryAttribute:NSBackgroundColorAttributeName forCharacterRange:oldRange];
}
for (NSValue *v in ranges) {
NSRange range = [v rangeValue];
if (range.length > 0)
[[self layoutManager] addTemporaryAttributes:[NSDictionary dictionaryWithObject:[NSColor blueColor] forKey:NSBackgroundColorAttributeName]
forCharacterRange:range];
}
[super setSelectedRanges:ranges affinity:affinity stillSelecting:stillSelectingFlag];
}
【讨论】:
stillSelecting)。如果要处理正在进行的选择,则需要子类化 NSTextView(编辑我的答案以提供一些示例代码)。