开发者

NSButton with variable size width, rounded corners

What is the best way to create an NSButton with a custom background image, 开发者_如何学Gothat 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];


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜