问题描述
我目前正在使用 XCode 12.3 和 Swift 5 开发 Swift/Cocoa 应用程序。
我已经尝试使用
更改设计self.window?.standardWindowButton(.closeButton)?.layer. ... = ...
但是这种方法似乎行不通——至少对我来说是这样。您对如何使其成为可能有任何想法吗?
解决方法
您需要将 wantsLayer
设置为 true
。标准窗口按钮是内部带有 NSButton
的常规 NSCell
。要自定义而不是让原始按钮阻止视图,您需要删除单元格并使用图层或仅创建一个自定义图层。
请注意,在删除或设置您自己的按钮单元格时,其操作选择器将重置,因此您需要确保按钮仍然可以执行您想要的操作。
这是 Objective C 中的代码,但它应该很容易翻译成 Swift:
NSButton *button = [self standardWindowButton:NSWindowCloseButton];
button.wantsLayer = YES;
button.layer.backgroundColor = NSColor.greenColor.CGColor;
NSCell *cell = [[NSCell alloc] initTextCell:@"?"];
[button setCell:cell];