How can I format parts of a text in a NSTextView programmatically? For example, make all occurrences of the word "foo" blue or make all the text grey but the current paragraph (where the cursor is) solid black? Thanks
You can use NSAttributedString
or NSMutableAttributedString
just specify text format (color, text size, etc) and pass it to your NSTextView, for example:
NSString *str = @"test string";
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString: str];
NSDictionary *attributes = @{
NSForegroundColorAttributeName : [NSColor redColor],
NSFontAttributeName : [NSFont fontWithName:@"HelveticaNeue-Bold" size:12.0]
};
[attrString setAttributes:attributes range:NSMakeRange(0, str.length)];
[[self.myNSTextView textStorage] appendAttributedString: attrString];
That will set up all your text to be the same but just replace range attribute with the one you want to change only this part of the text: NSMakeRange(0, 2)
this will add just the text attributes to first two lerrers.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.