在NSTextView中更改特定子字符串的颜色

时间:2013-03-16 10:23:26

标签: macos cocoa nsstring nstextview

我想更改NSTextView中特定文本的颜色。该方法应该在keydown事件之后检查。

例如:单词void已完成,字符串void将更改 颜色为蓝色。就像代码编辑器一样。

我搜索了很长时间但没有找到任何东西。 我的代码:

 NSRange range = [text rangeOfString:@"void"];
 NSString *substring = [[text substringFromIndex:NSMaxRange(range)] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
 //I think, here is the mistake.
 NSAttributedString *now = [NSAttributedString initWithString:substring];
 [now setTextColor:[[NSColor blueColor]]];

我已经读过我必须使用NSAttributedString,但我不知道如何从字符串中获取此类。

我是可可编程的新手。

感谢您的帮助!

1 个答案:

答案 0 :(得分:5)

你可以这样做:

NSString *str = @"Hello. That is a test attributed string.";

//in place of NSMakeRange put your range

[self.textview setRichText:YES];
[self.textview setString:str];
[self.textview setTextColor:[NSColor redColor] range:NSMakeRange(3,5)];
相关问题