Question

I have my NSButton layer backed because I wanted to use a custom image, but this seems like it's inhibiting the use of the setFont: method when I need to programmatically change the font, as when I comment out the code for wantsUpdateLayer: and updateLayer:, setFont: works, but when the layer methods are in the code, it does nothing.

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    self.fontChangeButton = [[CustomButton alloc]initWithFrame:NSMakeRect(82, 60, 190, 113)];
    [self.window.contentView addSubview:self.fontChangeButton];
}

- (IBAction)changeFont:(id)sender {
    [self.fontChangeButton fontChange];
}
@end

@implementation CustomButton

- (void)fontChange{
    [self setFont:[NSFont fontWithName:@"Dosis Bold" size:40]];
}

//when these are commented out, setFont: works, but I need them in for the custom button images
- (BOOL)wantsUpdateLayer{
    return YES;
}
- (void)updateLayer{
    if (self.state == NSOnState) {
        self.layer.contents = [NSImage imageNamed:@"buttonPressed.png"];
    }else
        self.layer.contents = [NSImage imageNamed:@"buttonUnpressed.png"];
}

This thread offers a workaround, but I'd much rather understand why this is happening and fix it: Can't Change NSButton Font

No correct solution

OTHER TIPS

By overriding -wantsUpdateLayer to return YES you're bypassing calls to -drawRect:. This facility was introduced in 10.8 and exists for efficiency purposes.

There are two things I think should be clarified:

1 - You don't need to override -wantsUpdateLayer to be layer-backed. Just send -setWantsLayer:YES to your button to be layer-backed.

2 - In your example, creating a custom NSButtonCell class might be a better approach to what you're trying to do. Have a look at Apple's documentation on subclassing NSControl and this how to to get started.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top