How to set the font of NSMenu/NSMenuItems?

折月煮酒 提交于 2019-12-05 08:41:29

They can have an attributed title, so you can set an attributed string as title with all it's attributed, font included:

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

NSMenuItem has support for attributed strings as titles:

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

Example code:

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

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

+ menuBarFontOfSize: from NSFont is your friend here.

  • If you don't plan to change the font family, you should use [NSFont menuBarFontOfSize:12] to get the default font and set a new size.
  • If you are only changing the color, you still need to set the default font size back by doing [NSFont menuBarFontOfSize:0].

So to only change the NSMenuItem color:

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

NSAttributedString *attributedTitle = [[NSAttributedString alloc] initWithString:[menuItem title] attributes:attributes];
[menuItem setAttributedTitle:attributedTitle];

Actually [NSMenu setFont:] works for all menu items submenus (if last ones doesn't have their own font). Maybe you set attributed title before setting the menu font? Realized it, after writing own procedure to iterate through menu items.

In case you need some custom processing (i.e. change font for not all items, or customize it for different items) here is a simple iterating code:

@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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!