1

I wonder if it's possible to show live fonts in a popupbutton control (NSPopupButton)? currently, I load a popupbutton with a list of fonts available in the following manner.

NSArray *familyNames = [[NSFontManager sharedFontManager] availableFontFamilies];
NSMutableArray *fontarray = [[NSMutableArray alloc] initWithObjects:nil];
[fontarray addObject:@"- Select one - "];
for (NSString *family in familyNames) {
    [fontarray addObject:family];
}
[fontmenu1p addItemsWithTitles:fontarray];

Maybe, something like the following, using NSMutableAttributedString?

for (NSString *family in familyNames) {
    NSDictionary *attr1 = [NSDictionary dictionaryWithObjectsAndKeys:[NSFont fontWithName:family size:[NSFont systemFontSize]],NSFontAttributeName,[NSColor blackColor],NSForegroundColorAttributeName,nil];
    NSMutableAttributedString *aString = [[NSMutableAttributedString alloc] initWithString:family];
    [aString setAttributes:attr1 range:NSMakeRange(0,family.length-1)];
    [fontarray addObject:aString];
}
[fontmenu1p addItemsWithTitles:fontarray];

I get an out of bounds error. I don't know if my approach is right. I don't even know if the popupbutton control supports styled text.

Thank you for your help.

4

1 回答 1

3

即使我没有测试它,我认为我们的方法也行不通。NSPopUpButton 的菜单有一个方便的 API。方便,但很短。(通常弹出项目没有属性,没有单独的视图等。)

我会尝试为每个项目构建一个NSMenuItem实例。有一个 setter -setAttributedTitle:,它可以让你设置属性字符串。然后你必须将它聚合到一个NSMenu的实例,并将菜单设置为弹出按钮。

顺便说一句:[aString setAttributes:attr1 range:NSMakeRange(0,family.length-1)]; 为什么是-1?长度是长度,而不是最后一个字符的索引。而且你想设置一个范围,它也需要长度,而不是最后一个字符的索引。

于 2013-06-22T17:25:35.670 回答