6

我不知道如何在我的 NSMenu 中设置我的 NSMenuItems 的字体/样式。我在 NSMenu 上尝试了 setFont 方法,但它似乎对菜单项没有任何影响。NSMenuItem 似乎没有 setFont 方法。我希望它们都具有相同的字体/样式,所以我希望我可以在某处设置一个属性。

4

4 回答 4

8

NSMenuItem 支持属性字符串作为标题:

- (void)setAttributedTitle:(NSAttributedString *)string;

示例代码:

NSMenuItem *menuItem = [[NSMenuItem alloc] initWithTitle:@"Hi, how are you?" action:nil keyEquivalent:@""];
NSDictionary *attributes = @{
                              NSFontAttributeName: [NSFont fontWithName:@"Comic Sans MS" size:19.0],
                              NSForegroundColorAttributeName: [NSColor greenColor]
                            };
NSAttributedString *attributedTitle = [[NSAttributedString alloc] initWithString:[menuItem title] attributes:attributes];
[menuItem setAttributedTitle:attributedTitle];

文档:https ://developer.apple.com/library/mac/#documentation/cocoa/reference/applicationkit/classes/nsmenuitem_class/reference/reference.html

于 2012-11-19T17:34:08.437 回答
8

它们可以具有属性标题,因此您可以将属性字符串设置为标题,其中包含所有属性,包括字体:

NSMutableAttributedString* str =[[NSMutableAttributedString alloc]initWithString: @"Title"];
[str setAttributes: @{ NSFontAttributeName : [NSFont fontWithName: @"myFont" size: 12.0] } range: NSMakeRange(0, [str length])];
[label setAttributedString: str];
于 2012-11-19T17:35:54.593 回答
4

+ menuBarFontOfSize:fromNSFont是你的朋友。

  • 如果您不打算更改字体系列,则应使用[NSFont menuBarFontOfSize:12]获取默认字体并设置新大小。
  • 如果您只是更改颜色,您仍然需要通过执行[NSFont menuBarFontOfSize:0].

所以只改变NSMenuItem颜色:

NSDictionary *attributes = @{
                              NSFontAttributeName: [NSFont menuBarFontOfSize:0],
                              NSForegroundColorAttributeName: [NSColor greenColor]
                            };

NSAttributedString *attributedTitle = [[NSAttributedString alloc] initWithString:[menuItem title] attributes:attributes];
[menuItem setAttributedTitle:attributedTitle];
于 2015-10-03T01:24:12.273 回答
1

实际上[NSMenu setFont:]适用于所有菜单项子菜单(如果最后一个没有自己的字体)。也许您在设置菜单字体之前设置了属性标题?实现它,在编写自己的程序来遍历菜单项之后。

如果您需要一些自定义处理(即更改并非所有项目的字体,或为不同项目自定义字体),这里有一个简单的迭代代码:

@implementation NSMenu (MenuAdditions)

- (void) changeMenuFont:(NSFont*)aFont
{
    for (NSMenuItem* anItem in self.itemArray)
    {
        NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObject:aFont forKey:NSFontAttributeName];
        anItem.attributedTitle = [[[NSAttributedString alloc] initWithString:anItem.title attributes:attrsDictionary] autorelease];

        if (anItem.submenu)
            [anItem.submenu changeMenuFont:aFont];
    }
}

@end
于 2014-02-25T09:35:34.567 回答