I set some default font and color to a NSTextView inside of a NSPanel.
However, when I clear the view with setString:@""
, not only does the text disappears, but all the default colors/fonts formatting.
After I do another setString
, the text becomes the default font and black again.
Can someone explain why that is and what can I do to remedy it?
UPDATED:
Thanks for the help and clarification of the issue.
I ended up just formatting it again after I setString.
[self.txtLog setFont:[NSFont fontWithName:@"courier" size:12]];
[self.txtLog setTextColor:[NSColor colorWithSRGBRed:65.0/255 green:229.0/255 blue:235.0/255 alpha:1]];
It is because clearing the NSTextView and setting a regular (non-attributed) string removes the formatting, which includes font and color.
Most of the time, I set attributed strings that I format using HTML. I find it to be very convenient. For instance, here are two macro I use to set the color and the font:
#define color(string, color) strAdd5(@"<font color=\"#",(color), @"\">", (string), @"</font>")
#define fontName(string, fontname) strAdd5(@"<span style=\"font-family: ",(fontname), @";\">", (string), @"</span>")
#define html2AttributedString(htmlString) [[[NSAttributedString alloc] initWithHTML:[(htmlString) dataUsingEncoding:NSUTF8StringEncoding]documentAttributes:NULL] autorelease]
Then, all I need is to set the attributed string in the text storage:
[textStorage setAttributedString:html2AttributedString(color(myNSString, @"FF0000"))]
or to use insertText of NSTextView
[textView insertText:html2AttributedString(fontName(myNSString, @"Courier New"))];
And using HTML, you can define everything including centering, and many other properties. But, you have to convert any new lines into < BR / > before converting the text.