NSPopButton with list of font families

三世轮回 提交于 2019-12-11 02:23:40

问题


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


来源:https://stackoverflow.com/questions/30185423/nspopbutton-with-list-of-font-families

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!