NSPopButton with list of font families

2019-07-24 17:38发布

问题:

How can I create a NSPopupButton with a list of font families where each item is in its own font as shown in the attached screenshot. I want to use bindings to achieve this.

I am able to populate the NSPopupButton by binding NSPopupButton content to value returned by [[NSFontManager sharedFontManager] availableFontFamilies] but I can't figure out how to get each individual row in its own font?

回答1:

I wasn't sure I could do it, but the following appears to work.

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