5

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.

BadPirate
  • 25,802
  • 10
  • 92
  • 123

3 Answers3

7

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.

BadPirate
  • 25,802
  • 10
  • 92
  • 123
2

this worked perfectly fine for me:

[self.addBuddyCommitButton.cell setBezelStyle:NSRoundedBezelStyle];
martyglaubitz
  • 992
  • 10
  • 21
1

NSButton doesn't have the same convenience methods for background images as UIButton (which is odd and here's to hoping Apple bridges that gap). You'll need to create a custom button my subclassing NSView and handling the variable width and corners yourself. I don't think it will be easy, but I don't think it would be terribly difficult either.

Philip Regan
  • 5,005
  • 2
  • 25
  • 39