El Tomato
El Tomato

Reputation: 6707

NSPopupButton with Live Fonts (Styled Text)

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.

Upvotes: 1

Views: 878

Answers (1)

Amin Negm-Awad
Amin Negm-Awad

Reputation: 16650

Even I did not tested it, I think, that our approach will not work. NSPopUpButton has a convenient API for its menu. Convenient, but short. (Typically pop-up items are not attributed, no separate views and so on.)

I would try to build an instance of NSMenuItem for each item. There is a setter -setAttributedTitle:, which lets you set attributed strings. Then you have to aggregate this to an instance of NSMenu and set the menu to the pop-up button.

BTW: [aString setAttributes:attr1 range:NSMakeRange(0,family.length-1)]; Why -1? The length is the length, not the index of the last char. And you want to set a range, which takes the length, not the index of the last character, too.

Upvotes: 3

Related Questions