【问题标题】:NSButton: blue background [duplicate]NSButton:蓝色背景[重复]
【发布时间】:2021-09-11 00:16:48
【问题描述】:

我想让我的 NSButton 看起来像 Xcode 的提交按钮

但似乎没有任何方法可以轻松更改 NSButton 的背景颜色。您必须将“边框”更改为“否”,然后设置按钮的背景颜色,并为按钮设置“属性标题”以使 textColor 变为白色。但是当我这样做时,结果看起来一点也不接近:

按钮没有任何阴影;文本看起来不居中;它也不支持在选择按钮时更改背景颜色,就像 Xcode 中的按钮一样。

这肯定很容易复制,因为我相信我在整个系统中都看到过类似的按钮。

这是我为此编写的 NSButton 子类:

override func awakeFromNib() {
    super.awakeFromNib()
    self.wantsLayer = true
    self.isBordered = false //Important
    self.layer?.backgroundColor = backgroundColor.cgColor
    self.layer?.cornerRadius = 6.0
    
    let font = NSFont.systemFont(ofSize: 14, weight: .medium)
    let fontColor = NSColor.white
    
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = .center

    self.attributedTitle = NSAttributedString(string: self.title, attributes: [NSAttributedString.Key.foregroundColor : fontColor,
        NSAttributedString.Key.font: font, NSAttributedString.Key.paragraphStyle : paragraphStyle]) // to update text, have to update the attributeString's mutableString property
}

很想知道我在哪里出错了。我原以为我需要一个带有边框和阴影效果的常规“按钮”按钮,但背景为蓝色,但从我所看到的情况来看,这似乎并不直接。

谢谢。

【问题讨论】:

标签: macos appkit nsbutton


【解决方案1】:

因此找到了我正在寻找的“简单”解决方案:无需对 NSButton 层进行任何调整。您只需将键设置为等效于“返回”键!

[self.editButton setKeyEquivalent: @"\r"];

这会将按钮背景颜色设置为蓝色,并按我希望的那样工作。如果你想要一些其他的背景颜色,我想你必须像上面那样自定义按钮。

【讨论】:

  • ..现在我们也在 Obj-C 中使用属性,如果我们不再使用它的话。
猜你喜欢
  • 2011-12-07
  • 1970-01-01
  • 2017-03-27
  • 2021-08-18
  • 1970-01-01
  • 1970-01-01
  • 2016-06-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多