众所周知NSButton不同于UIButton,哪怕是想设置一下字体颜色通常都要写一个新类继承NSButton,然后对其定制。这里分享一个简洁的方案。
Github Gist
Stackoverflow 讨论
code (Swift 3实现)
extension NSButton {
var titleTextColor : NSColor {
get {
let attrTitle = self.attributedTitle
return attrTitle.attribute(NSForegroundColorAttributeName, at: 0, effectiveRange: nil) as! NSColor
}
set(newColor) {
let attrTitle = NSMutableAttributedString(attributedString: self.attributedTitle)
let titleRange = NSMakeRange(0, self.title.characters.count)
attrTitle.addAttributes([NSForegroundColorAttributeName: newColor], range: titleRange)
self.attributedTitle = attrTitle
}
}
}
使用范例
someButton.titleTextColor = NSColor.yellow
背景颜色呢?
设置NSButton的背景颜色相对简单,可以利用CALayer的backgroundColor属性达到目的,前提是NSButton是Borderless的。
someButton.layer?.backgroundColor = NSColor.red.cgColor