【问题标题】:Swift Cocoa manipulate design of titlebar buttonsSwift Cocoa 操纵标题栏按钮的设计
【发布时间】:2021-04-25 00:48:17
【问题描述】:

我目前正在使用 XCode 12.3 和 Swift 5 开发 Swift/Cocoa 应用程序。

我想在 NSWindow 的标题栏中操作关闭按钮的设计。

我已经尝试过使用

来改变设计
self.window?.standardWindowButton(.closeButton)?.layer. ... = ...

但这种方法似乎行不通——至少对我来说是这样。您对如何实现它有任何想法吗?

【问题讨论】:

    标签: swift xcode cocoa nswindow titlebar


    【解决方案1】:

    您需要将wantsLayer 设置为true。标准窗口按钮是常规的NSButtons,其中包含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];
    

    结果:

    【讨论】:

    • 非常感谢您的回答!这完全是我想要的。我已经发现我必须将 WantLayer 设置为 true,但我不知道这些按钮中有一个 NSCell。
    猜你喜欢
    • 2010-11-22
    • 1970-01-01
    • 1970-01-01
    • 2014-10-13
    • 1970-01-01
    • 1970-01-01
    • 2014-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多