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.
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.
this worked perfectly fine for me:
[self.addBuddyCommitButton.cell setBezelStyle:NSRoundedBezelStyle];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With