Chris
Chris

Reputation: 547

Change the Color of specific substrings in NSTextView

I want to change the color of specific text in NSTextView. The method should check that after a keydown event.

For example: the word void is finished and the string void changes the color to blue. Like a code editor.

I searched for a long time but don't find anything. My Code:

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

I have read that i have to use a NSAttributedString but i don't know how I can get this class from a string.

I'am quite new in cocoa programming.

Thanks for every help!

Upvotes: 3

Views: 2448

Answers (1)

Anoop Vaidya
Anoop Vaidya

Reputation: 46563

You can do this way:

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

Upvotes: 5

Related Questions