views:

30

answers:

1

Hi all,

I am displaying buttons in NSMatrix.

My requirement is:

to change color of button title and place an image at beginning of title, when certain condition is satisfied.

To do so, I used following code:

// setting  attributed text
            NSAttributedString *selectedCellAttribute;

            NSFont *selectedCellFont = [NSFont fontWithName:@"Lucida Grande" size:11];
            NSColor *selectedCellColor = [NSColor redColor];
            NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
            [style setAlignment:NSCenterTextAlignment];

            // setting image
            NSTextAttachment *imageAttachment = [[NSTextAttachment alloc] init];
            NSCell *cell = [imageAttachment attachmentCell];
            [cell setImage:[NSImage imageNamed:@"caution_small.png"]];

            NSDictionary *selectedCellDictionary = [NSDictionary dictionaryWithObjectsAndKeys:imageAttachment,NSAttachmentAttributeName,selectedCellFont,NSFontAttributeName,selectedCellColor,NSForegroundColorAttributeName,style,NSParagraphStyleAttributeName,nil];

            // recognizing cell

            NSButtonCell *associatedCell = [associatesMatrix cellAtRow:0 column:2];
            selectedCellAttribute = [[NSAttributedString alloc] initWithString:[associatedCell title] attributes:selectedCellDictionary];
            [associatedCell setAttributedTitle:selectedCellAttribute];

Although above code is showing change in color of title, it is showing no image placed in beginning of title :(

Can anyone suggest me where I may be wrong or some other method to implement my requirements?

EDIT:

At line:

NSCell *cell = [imageAttachment attachmentCell];

it is giving this warning when compiled:

type 'id <NSTextAttachmentCell>' does not conform to 'NSCopying" protocol.

Thanks,

Miraaj

+1  A: 

You've set the attachment for the entire string. What you need to do is prefix the string with NSAttachmentCharacter, and set the attachment only for that section of the string.

You may want to put a space between the NSAttachmentCharacter and your actual text. Only the NSAttachmentCharacter should have the attachment attribute.

Peter Hosey
can you suggest some code (as an example) to do that ?
Miraaj
http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSMutableAttributedString_Class/
Peter Hosey
I have looked at class reference of NSAttributedString but in it I am getting no clue about how to use NSAttachmentCharacter :(
Miraaj
You need to insert it at the start of the string, and apply the attachment attribute to it.
Peter Hosey