如何设置NSMenu / NSMenuItems的字体?

问题描述 投票:5回答:4

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

objective-c cocoa interface-builder nsmenuitem nsmenu
4个回答
8
投票

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

NSMutableAttributedString* str =[[NSMutableAttributedString alloc]initWithString: @"Title"];
[str setAttributes: @{ NSFontAttributeName : [NSFont fontWithName: @"myFont" size: 12.0] } range: NSMakeRange(0, [str length])];
[label setAttributedString: str];

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


3
投票

+ menuBarFontOfSize:NSFont是您的朋友在这里。

  • 如果您不打算更改字体系列,则应使用[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];

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
© www.soinside.com 2019 - 2024. All rights reserved.