【问题标题】:Showing image before text in NSButtonCell in NSMatrix在 NSMatrix 中的 NSButtonCell 中的文本之前显示图像
【发布时间】:2011-04-02 11:50:20
【问题描述】:

我在 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.

谢谢,

米拉杰

【问题讨论】:

  • 如果您不使用 GC,请不要忘记释放可变段落样式、附件和属性字符串。
  • 感谢您的回复...该应用程序已启用 GCC!
  • 你是说GC吗? GCC 是 GNU 编译器集合,与您使用的编译器无关。 GC 是垃圾收集,在这种情况下,发送 Objective-C release 消息并不是绝对必要的(但不这样做是一个很好的方式来温和地提醒你“如果你不使用 GC,你需要释放那些东西”当你在 Stack Overflow 上发布代码☺)。

标签: cocoa nsattributedstring nsbuttoncell nsmatrix


【解决方案1】:

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

您可能希望在NSAttachmentCharacter 和您的实际文本之间放置一个空格。只有NSAttachmentCharacter 应该有附件属性。

【讨论】:

猜你喜欢
  • 2011-01-05
  • 2023-03-26
  • 2017-02-24
  • 1970-01-01
  • 1970-01-01
  • 2013-02-14
  • 1970-01-01
  • 1970-01-01
  • 2015-06-26
相关资源
最近更新 更多