带有字体系列列表的NSPopButton

时间:2015-05-12 08:20:50

标签: objective-c macos cocoa cocoa-bindings

如何创建带有字体系列列表的NSPopupButton,其中每个项目都有自己的字体,如附带的屏幕截图所示。我想使用绑定来实现这一目标。

我可以通过将NSPopupButton内容绑定到[[NSFontManager sharedFontManager] availableFontFamilies]返回的值来填充NSPopupButton,但我无法弄清楚如何以自己的字体获取每一行?

enter image description here

1 个答案:

答案 0 :(得分:4)

我不确定我能做到,但以下似乎有效。

// fontPopup1 is an instance of NSPopupMenu
NSMenu *menu = [[NSMenu alloc] init];
NSArray *familyNames = [[NSFontManager sharedFontManager] availableFontFamilies];
NSMutableArray *fontArray = [[NSMutableArray alloc] initWithObjects:nil];
for (NSString *family in familyNames) {
    [fontArray addObject:family];
}
for (NSInteger i2 = 0; i2 < fontArray.count; i2++) {
    NSString *family = [fontArray objectAtIndex:i2];
    NSMutableAttributedString *attrStr =[[NSMutableAttributedString alloc]initWithString:family];
    CGFloat fontSize = [NSFont systemFontSize];
    [attrStr addAttribute:NSFontAttributeName value:[NSFont fontWithName:family size:fontSize] range:NSMakeRange(0,family.length)];
    NSMenuItem *menuItem = [[NSMenuItem alloc] init];
    [menuItem setAttributedTitle:attrStr];
    [menu addItem:menuItem];
}
[fontPopup1 setMenu:menu];