8

在使用自定义图像和备用图像创建 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 窗口的斜角按钮:
覆盖 HUD 窗口的斜角按钮

错误的斜角按钮背景:
错误的斜角按钮背景

4

4 回答 4

25

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

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

于 2012-02-26T14:31:08.817 回答
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 中测试)。

于 2016-02-23T21:16:03.850 回答
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];
于 2011-10-13T17:54:11.173 回答
1

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

于 2015-10-06T12:49:28.367 回答