单击时NSButton白色背景

时间:2011-10-13 15:12:11

标签: cocoa nsbutton nsbuttoncell

使用自定义图像和替代图像创建Cocoa斜角按钮时,我有一种奇怪的行为。在按下状态下,按钮背景变为白色。 我正在添加按钮作为透明窗口(HUD窗口)的子视图。

我正在尝试我所知道的每一项技术:

NSButton *closeButton = [[NSButton alloc] initWithFrame:NSMakeRect(0.0, 0.0, 30.0, 30.0)];
        [closeButton setFrameOrigin:NSMakePoint(0.0, 0.0)];
        [closeButton setImagePosition:NSImageOnly];
        [closeButton setAction:@selector(closeWindowAction:)];
        [closeButton setBordered:NO];
        [closeButton setTransparent:NO];

        [closeButton setImage:[NSImage imageNamed:@"icon-tclose-off"]];
        [closeButton setAlternateImage:[NSImage imageNamed:@"icon-tclose-on"]];
        [closeButton setBezelStyle:NSShadowlessSquareBezelStyle];
        [closeButton setButtonType:NSMomentaryLightButton];

        //[[closeButton cell] setBackgroundColor:[NSColor clearColor]];
        [[closeButton cell] setHighlightsBy:NSChangeBackgroundCellMask|NSCellLightsByContents];
        //[[closeButton cell] setHighlightsBy:NSContentsCellMask];
        //[[closeButton cell] setShowsStateBy:0|NSContentsCellMask];

我也试过

[closeButton setButtonType:NSMomentaryChangeButton];

[[closeButton cell] setHighlightsBy:NSContentsCellMask];

没有结果。

您可以在附加的屏幕截图中看到错误的行为:

覆盖HUD窗口的斜角按钮:
Bevel button overlaying a HUD window

错误的斜角按钮背景:
Wrong Bevel button background

4 个答案:

答案 0 :(得分:25)

根据您的具体情况,这可能也有效:

将按钮的样式更改为斜角或方形,模式应设置为“瞬间更改”,边框,透明,混合和选定应为OFF。这就是我在按钮上修复白色背景问题的方法。

答案 1 :(得分:4)

我已将cell.highlightsBy设为ContentsCellMask

,使其成功
let btn = NSButton(frame: myFrame)

btn.image = myButtonImage
btn.image?.size = myFrame.size
btn.imagePosition = .ImageOnly

btn.bordered = false      
(btn.cell as? NSButtonCell)?.highlightsBy = .ContentsCellMask

view.addSubview(btn)

这样按下时按钮会变暗,但不会出现难看的方块。仅在El Capitan测试过。

答案 2 :(得分:2)

创建按钮

NSButton *myButton;
myButton = [[NSButton new] autorelease];
[myButton setTitle: @"Hello!"];
[myButton sizeToFit];
[myButton setTarget: self];
[myButton setAction: @selector (function:)];

向窗口添加按钮

unsigned int styleMask = NSTitledWindowMask 
                           | NSMiniaturizableWindowMask;
NSWindow *myWindow;
myWindow = [NSWindow alloc];
/*get the size of the button*/
NSSize buttonSize;
buttonSize = [myButton frame].size;
/*set window content rect with the size of the button, and with an origin of our choice; (100, 100)*/
NSRect rect;
rect = NSMakeRect (100, 100, 
                   buttonSize.width, 
                   buttonSize.height);

myWindow = [myWindow initWithContentRect: rect
                       styleMask: styleMask
                       backing: NSBackingStoreBuffered
                       defer: NO];
[myWindow setTitle: @"my window"];
/*replacing the default window content view with our button*/
[myWindow setContentView: myButton];

答案 3 :(得分:1)

您应该设置按钮类型: myButton.buttonType = NSMomentaryChangeButton;