2011-10-13 33 views
8

当用自定义图像和替代图像创建Cocoa斜角按钮时,我有一个奇怪的行为。在按下状态下,按钮背景变成白色。 我将该按钮添加为透明窗口(HUD窗口)的子视图。点击时NSButton白色背景

我想每一个技术,我知道:

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

回答

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]; 
+0

我不清楚这是NSWindow myWindow。它是按钮容器吗?在这种情况下,它的内容矩形是你定义的NSRect矩形? – loretoparisi

+0

现在清楚了吗? –

+0

听起来不错! – loretoparisi

25

添加按钮,根据您的情况,这也可能工作:

更改按钮斜角或广场的风格,模式应设置为“瞬间变”与边境,透明,混合和选择应该关闭。这是我如何解决我的按钮上的白色背景问题。

+0

这是Mac OS 10.12的问题,但不是10.13。 – samatron

1

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

4

我已通过设置cell.highlightsByContentsCellMask工作:

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) 

这样按下按钮时变黑了,但没有丑陋的广场出现。仅在埃尔卡皮坦测试)。

+0

您还可以添加'btn.alternateImage = myButtonAlternateImage',它会显示何时按下按钮 –