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

标签 cocoa nsattributedstring nsbuttoncell nsmatrix

我正在 NSMatrix 中显示按钮。

我的要求是:

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

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

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

谢谢

米拉杰

最佳答案

您已为整个字符串设置了附件。您需要做的就是在字符串中添加 NSattachmentCharacter 前缀,并仅为字符串的该部分设置附件。

您可能需要在 NSattachmentCharacter 和实际文本之间放置一个空格。只有 NSattachmentCharacter 应该具有附件属性。

关于cocoa - 在 NSMatrix 中的 NSButtonCell 中的文本之前显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3545218/

相关文章:

bash - 如何要求 Cocoa 应用程序从终端运行一个操作然后返回结果

swift - Swift OSX 新增功能 : NSImageView Drawing multiple images with drawInRect - Can't update image

ios - NSForegroundColorAttributeName 不适用于 UILabel

ios - 更改字符串中特定单词的颜色

cocoa - NSButtonCell 与 NSButton

cocoa - NSTableView 中的 NSButtonCell : click handling

objective-c - Cocoa Obj-C 中的类设计和对象字面量

swift - cocoa swift : Error evaluateJavaScript Optional ("A JavaScript exception occurred")

iphone - 使用 Core Text 为给定的字符串范围设置背景颜色/突出显示颜色

cocoa - 防止 NSButtonCell 图像在其包含的 NSScrollView 之外绘制