I'm trying to use a font panel in my Cocoa app and I can't get the changeFont: method to be called.
I had it working properly in another app and I just copied and pasted the code over but for some odd reason the changeFont method isn't called now. Here's the code:
- (IBAction)onOpenFontPanelBtnClicked:(id)sender
{
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
NSString* theFontName = [defaults objectForKey:DefaultFontNamePrefKey];
NSFont* theFont = [NSFont fontWithName:theFontName size:12.0f];
NSFontManager* fontMgr = [NSFontManager sharedFontManager];
[fontMgr setTarget:self];
[fontMgr setAction:@selector(changeMyCustomFont:)];
NSFontPanel* panel = [fontMgr fontPanel:YES];
[panel setPanelFont:theFont isMultiple:NO];
[panel orderFront:self];
panel.enabled = YES;
NSLog(@"Font manager target: %@ (class: %@), action: %@", fontMgr.target, [fontMgr.target className], NSStringFromSelector(fontMgr.action));
}
- (void) changeMyCustomFont:(id)sender
{
NSLog(@"New font: %@", [[NSFontManager sharedFontManager] selectedFont]);
}
This code is being called from a view controller inside a modal window (preference window) and the font panel opens just fine. However, I'm not getting any changes although I set the target and action manually.
Is this problem related to the responder chain? How can I fix it? Do I need to manually add the view controller to the responder chain? How would I do so?
Thanks in advance!
Answering my own question to help others that stumble upon this in the feature. As I assumed, this issue was related to the responder chain.
My hierarchy was as follows: NSWindow (managed by NSWindowController) -> contentView -> childview (managed by NSViewController)
I found out that the responder chain ended in the window controller. Thus, the font panel wasn't able to send the changeFont: message to the view controller where I implemented it.
By adding this line of code in the window controller I could fix the issue:
What I still don't understand though is why it doesn't work when I manually configure target/action. Anyways, it works for me now.