macoscocoansbutton

How to modify look and feel of NSButton to create toggle effect


How to modify look and feel of NSButton, I want to create a toggle button which looks similar to NSRoundRectBezelStyle but with Image and custom height

How do i change background color, color change on hover, change color on click, create toggle effect when state is ON or OFF, create border which is similar to NSRoundRectBezelStyle. Existing native button doesn't have exact UI as that of my UI Element.

UI should look something like below, but I want to add Image above text also.

enter image description here

This Mac Button - Hover effect

Desktop Button - Toggle ON effect

Shared Button - Toggle OFF effect


Solution

  • You can achieve this by creating a NSButton with the following attributes:

    Style: "Push"; Type: "Push On Push Off"; Bordered: "Yes"

    And subclassing NSButton and overriding few of its methods.

    - (instancetype)initWithCoder:(NSCoder *)coder
    {
        self = [super initWithCoder:coder];
        if(self)
        {
            self.showsBorderOnlyWhileMouseInside = YES;
        }
        return self;
    }
    
    - (void)setState:(NSControlStateValue)state
    {
        if(state == NSControlStateValueOn)
        {
            self.showsBorderOnlyWhileMouseInside = NO;
        }
        else
        {
            self.showsBorderOnlyWhileMouseInside = YES;
        }
    }
    

    This will yield a result as such:

    Toggle OFF effect

    enter image description here

    Hover effect

    enter image description here

    Toggle ON effect

    enter image description here

    Happy Coding!!!