在NSMatrix中的NSButtonCell中显示文本之前的图像

时间:2010-08-23 06:41:14

标签: cocoa nsattributedstring nsbuttoncell nsmatrix

我在NSMatrix中显示按钮。

我的要求是:

  

更改按钮标题的颜色和   当满足某些条件时,在标题的开头放置图像。

为此,我使用了以下代码:

// 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];

虽然上面的代码显示了标题颜色的变化,但是在标题的开头没有显示任何图像:(

有人可以建议我可能出错的地方或其他方法来实现我的要求吗?

编辑:

在线:

NSCell *cell = [imageAttachment attachmentCell];

编译时会发出此警告:

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

谢谢,

Miraaj

1 个答案:

答案 0 :(得分:1)

您已为整个字符串设置附件。您需要做的是在字符串前加NSAttachmentCharacter,并仅为字符串的该部分设置附件。

您可能希望在NSAttachmentCharacter和实际文字之间加一个空格。只有NSAttachmentCharacter应具有附件属性。