Mac formatting rich text (fonts, colors) in NSTableView

Oats

macrumors regular
Original poster
Jan 8, 2003
192
1
New York
I have an NSTableView with several entries, and I want to highlight certain words in the table. For example, every time the word "bar" appears in the table, I want that word to be bold and colored red, as in the example line below:

"foobar foo foo bar foo"

Any idea how I can accomplish this? Basically, I want to use rich text in the NSTableView cells. I was thinking of using the NSText method replaceCharactersInRange:withRTFD: but I really have no idea if this is correct. I would still need to figure out the RTF syntax, but thats a different story. Please help?
Thanks!
 

Oats

macrumors regular
Original poster
Jan 8, 2003
192
1
New York
Thanks! Once I have formatted a string, can I just use the (NSAttributedString *) instead of the (NSString *) when initializing the NSTableView dictionary?
 

robbieduncan

Moderator emeritus
Jul 24, 2002
24,638
61
Harrogate
Thanks! Once I have formatted a string, can I just use the (NSAttributedString *) instead of the (NSString *) when initializing the NSTableView dictionary?
I'm not sure what you mean by that. Could you post the code? NSTableViews don't have dictionaries :confused:
 

Oats

macrumors regular
Original poster
Jan 8, 2003
192
1
New York
I'm not sure what you mean by that. Could you post the code? NSTableViews don't have dictionaries :confused:
i am obviously new to this, my dictionary comment was referring to a NSMutableDictionary, which i believe has the contents binding to the NSTableView. as it turns out, i was able to just use a NSAttributedString in place of the NSString, and this works! the sample code here is probably convoluted... i know HTML, not RTF, so this seemed the easiest way to format my string?


PHP:
NSArray * keys      = [NSArray arrayWithObjects: @"linenum", @"linestr", nil];
//NSArray * values    = [NSArray arrayWithObjects: linenum, linestr, nil];
NSString * theHTML = @"<font face='Monaco' size='3'>foo foo foo<b><i><font color=#EE0000>bar</font></i></b> fooobar</font>";
// fill the NSData buffer with the contents of the NSString
NSData * htmlData = [theHTML dataUsingEncoding: NSUTF8StringEncoding];
NSAttributedString * styledText = [[NSAttributedString alloc]
				initWithHTML: htmlData  documentAttributes: nil]; 
NSArray * values    = [NSArray arrayWithObjects: linenum, styledText, nil];
properties = [[NSMutableDictionary alloc] initWithObjects: values forKeys: keys];
 

kainjow

Moderator emeritus
Jun 15, 2000
7,958
3
Easier != better.

Personally, I'd just build the attributed string manually, using initWithString:attributes:, and then combine the different attributed strings together to make the final attributed string (see NSMutableAttributedString). To me, that seems like the right "Cocoa way".