macos - NSButton custom style programmatically <OSX / Objective-C>


Keywords:objective  c 


Question: 

I have a problem with setting the button style,I have read Apple document already, but I still don't know how to change the style correctly.

Here is my code:

NSButton *loginBtn = [[NSButton alloc] initWithFrame:NSMakeRect(screenWidth / 2 - 155, screenHeight / 2 - 115, 300, 30)];
[loginBtn setCell:defaultButton];
[loginBtn setWantsLayer:YES];
[loginBtn setButtonType:NSButtonTypeMomentaryPushIn];
NSMutableAttributedString *buttonString = [[NSMutableAttributedString alloc] initWithString:@"Login" attributes:btnTextDictionary];
[loginBtn setAttributedTitle:buttonString];
[loginBtn setTarget:self];
[loginBtn setAction:@selector(loginActive)];
[loginView addSubview:loginBtn];

and I try to change background color by RGB, but not working:

[loginBtn.layer setBackgroundColor:[NSColor colorWithCalibratedRed:35 / 255.0f green:216 / 255.0f blue:202 / 255.0f alpha:1.0f]CGColor];

How can I set the BackgroundColor correctly with objective-c in "OSX application project"?


2 Answers: 

You cannot change the color of a bordered NSButton by setting the layer background. In your case, you probably need to set [loginBtn setBordered: NO];.

If you want a quicker and more versatile option to your solution, I've made a handy NSButton subclass called FlatButton that let's you create styled buttons easily straight from Interface Builder:

FlatButton for macOS

It's in Swift though.

 

For Objective-C here's a sub-class of NSButton that gives you a setBackgroundColor method.

MyButton.h

#import <Cocoa/Cocoa.h>

@interface MyButton : NSButton
@property (nonatomic, strong) NSColor *backgroundColor;
@end

MyButton.m

#import "MyButton.h"

@implementation MyButton

- (void)setBackgroundColor:(NSColor *)backgroundColor {
    _backgroundColor = backgroundColor;
    [self setNeedsDisplay];
}

- (void)drawRect:(NSRect)dirtyRect {
    [super drawRect:dirtyRect];    
    [_backgroundColor setFill];
    NSRectFill(dirtyRect);
}

@end

In your main code you can then do this:

#import "MyButton.h"

MyButton *loginBtn = [[MyButton alloc] initWithFrame:NSMakeRect(screenWidth / 2 - 155, screenHeight / 2 - 115, 300, 30)];
[loginBtn setBackgroundColor:[NSColor colorWithCalibratedRed:35 / 255.0f green:216 / 255.0f blue:202 / 255.0f alpha:1.0f]];