我不知道如何在NSMenu中设置NSMenuItem的字体/样式。我在NSMenu上尝试了setFont方法,但似乎对菜单项没有任何影响。 NSMenuItem似乎没有setFont方法。我希望它们都具有相同的字体/样式,所以我希望可以在某处设置一个属性。
它们可以具有属性标题,因此您可以将属性字符串设置为具有所有属性的标题,包括字体:
NSMutableAttributedString* str =[[NSMutableAttributedString alloc]initWithString: @"Title"];
[str setAttributes: @{ NSFontAttributeName : [NSFont fontWithName: @"myFont" size: 12.0] } range: NSMakeRange(0, [str length])];
[label setAttributedString: str];
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];
+ 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];
实际上[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