objective-cmacosstylesbackground-colornsbutton

NSButton custom style programmatically <OSX / Objective-C>


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"?


Solution

  • 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:

    https://github.com/OskarGroth/FlatButton

    FlatButton for macOS

    It's in Swift though.