众所周知NSButton不同于UIButton,哪怕是想设置一下字体颜色通常都要写一个新类继承NSButton,然后对其定制。这里分享一个简洁的方案。
Github Gist
https://gist.github.com/zhaorui/112ff42f52eb430ff7252a49b26343f9
Stackoverflow 讨论
http://stackoverflow.com/questions/13109964/nsbutton-how-to-color-the-text
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
对于有边框的NSButton,这种方法就行不通了,还是要走回继承NSButton的老路。原因详见Stackoverflow http://stackoverflow.com/questions/1017468/change-background-color-of-nsbutton