formatting rich text (fonts, colors) in NSTableView

Discussion in 'Mac Programming' started by Oats, Aug 1, 2007.

  1. macrumors regular

    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?
  2. Moderator


    Staff Member

    NSAttributedString allows you to add formatting to string objects. Most Cocoa cells and views will respect this when drawing, standard text cells do.
  3. macrumors regular

    Thanks! Once I have formatted a string, can I just use the (NSAttributedString *) instead of the (NSString *) when initializing the NSTableView dictionary?
  4. Moderator


    Staff Member

    I'm not sure what you mean by that. Could you post the code? NSTableViews don't have dictionaries :confused:
  5. macrumors G4


    I assume you mean the table content, and the answer to that is yes.
  6. macrumors regular

    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?

    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 dataUsingEncodingNSUTF8StringEncoding];
    NSAttributedString styledText = [[NSAttributedString alloc]
    initWithHTMLhtmlData  documentAttributesnil]; 
    NSArray values    = [NSArray arrayWithObjectslinenumstyledTextnil];
    properties = [[NSMutableDictionary allocinitWithObjectsvalues forKeyskeys];
  7. Moderator emeritus


    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".

Share This Page