Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSButton with variable size width, rounded corners

Tags:

cocoa

nsbutton

What is the best way to create an NSButton with a custom background image, that is able to have variable width, without making the corner bezel look stretched? I know there are convenience methods to do this with UIButton: http://jainmarket.blogspot.com/2009/04/create-uibuttonbutton-with-images.html but I haven't seen anything similar in NSButton.

like image 820
BadPirate Avatar asked Sep 17 '10 19:09

BadPirate


2 Answers

I needed to have a custom button background, here's how I did it. I made an NSButton subclass and overrode drawrect method:

- (void)drawRect:(NSRect)dirtyRect
{
    // My buttons don't have a variable height, so I make sure that the height is fixed
    if (self.frame.size.height != 22) {
        self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width,
                                22.0f);
    }
    // 
    switch (self.state) {
            // Onstate graphics
        case NSOnState:
            NSDrawThreePartImage(self.bounds, 
                                 [NSImage imageNamed:@"btnmain_lb_h.png"], [NSImage imageNamed:@"btnmain_bg_h.png"], [NSImage imageNamed:@"btnmain_rb_h.png"],
                                 NO, NSCompositeSourceAtop, 1.0, NO);
            // Offstate graphics
        default:
        case NSOffState:
            NSDrawThreePartImage(self.bounds, 
                                 [NSImage imageNamed:@"btnmain_lb.png"], [NSImage imageNamed:@"btnmain_bg.png"], [NSImage imageNamed:@"btnmain_rb.png"],
                                 NO, NSCompositeSourceAtop, 1.0, NO);
            break;
    }

    [super drawRect:dirtyRect];
}

Then I could put the buttons using Interface Builder, and to get the custom graphics I just have to change the class to my new subclass.

like image 107
BadPirate Avatar answered Oct 14 '22 10:10

BadPirate


this worked perfectly fine for me:

[self.addBuddyCommitButton.cell setBezelStyle:NSRoundedBezelStyle];
like image 44
martyglaubitz Avatar answered Oct 14 '22 11:10

martyglaubitz