Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 933
Chris Avatar asked Nov 26 '25 16:11

Chris


1 Answers

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)];
like image 70
Anoop Vaidya Avatar answered Nov 28 '25 17:11

Anoop Vaidya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!