NSButton宽度可变,圆角

Bad*_*ate 5 cocoa nsbutton

使用自定义背景图像创建NSButton的最佳方法是什么,它可以具有可变宽度,而不会使角落边框看起来拉伸?我知道有一些方便的方法可以使用UIButton:http://jainmarket.blogspot.com/2009/04/create-uibuttonbutton-with-images.html但我在NSButton中没有看到类似的东西.

Bad*_*ate 7

我需要一个自定义按钮背景,这是我如何做到的.我创建了一个NSButton子类并覆盖了drawrect方法:

- (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];
}
Run Code Online (Sandbox Code Playgroud)

然后我可以使用Interface Builder放置按钮,并获得自定义图形,我只需将类更改为我的新子类.