Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using NSFontPanel in Cocoa

I'm trying to use an NSFontPanel to allow the user to change an application-wide font setting. It's supposed to work something like this: the user clicks a button, a font panel pops up, they choose a font and a size, and their selection is persisted.

The following code shows the panel:

- (IBAction)showFontMenu:(id)sender {
    NSFontManager *fontManager = [NSFontManager sharedFontManager];
    [fontManager setDelegate:self];

    NSFontPanel *fontPanel = [fontManager fontPanel:YES];
    [fontPanel makeKeyAndOrderFront:sender];
}

The documentation seems to suggest that the changeFont:(id)sender method should be called when the font changes; this isn't happening in my case.

- (void)changeFont:(id)sender {
    // blah
}

Any ideas on what I might be doing wrong?

like image 977
conmulligan Avatar asked Sep 12 '09 17:09

conmulligan


4 Answers

include this:

[fontManager setTarget:self];
like image 124
Snow Avatar answered Nov 03 '22 06:11

Snow


The object you've defined -changeFont: on must the first responder or above it in the responder chain. You haven't specified where you've defined the method, but I assume it's on a controller object that is not in the responder chain.

like image 36
kperryua Avatar answered Nov 03 '22 06:11

kperryua


NSFontManager's delegate exists primarily to filter the fonts it supplies to the font panel via -fontManager:willIncludeFont:.

As kperryua mentions, -changeFont: is sent up the responder chain. The button that launches the font menu or its enclosing view might be a good place to put a responder for -changeFont:.

You might find the Font Handling guide marginally more useful than the Font Panel guide.

like image 1
Jeremy W. Sherman Avatar answered Nov 03 '22 06:11

Jeremy W. Sherman


The core problem is this line:

[fontPanel makeKeyAndOrderFront:sender];

By making the font panel the key window, it's got no idea where to send action messages like -changeFont: to.

like image 1
Xavave Avatar answered Nov 03 '22 05:11

Xavave