【发布时间】: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
}
很想知道我在哪里出错了。我原以为我需要一个带有边框和阴影效果的常规“按钮”按钮,但背景为蓝色,但从我所看到的情况来看,这似乎并不直接。
谢谢。
【问题讨论】:
-
已经发布了我找到的解决方案的答案。这与@Marek H 所指出的相同。