How to set the font of NSMenu/NSMenuItems?
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
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];
+ 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];