I can’t figure out how to set the font/styling of my NSMenuItems in my NSMenu. I tried the setFont method on the NSMenu but it doesn’t seem to have any effect on the menu items. NSMenuItem doesn’t seem to have a setFont method. I would like for them all to have the same font/style so I would hope there’s just one property I can set somewhere.
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
来源:https://stackoverflow.com/questions/13458963/how-to-set-the-font-of-nsmenu-nsmenuitems