NSButton设置字体颜色

众所周知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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 作为一个前端程序猿,下面这些站会让你眼前一亮。 amazeui框架组建丰富 http://amazeui.org...
    欧巴冰冰阅读 8,930评论 18 303
  • 概述 花了一天多粗略的翻了《图解密码技术》,图解系列真是入门神书,能够迅速的建立起一门学科的体系,强烈推荐。 一些...
    zengfan阅读 808评论 0 1
  • 如你所愿情如雪恨如铁风吹昭化万里飘雪 三生石畔千年劫生死别菩提树下七情六欲绝 眉心一点朱砂霜侵两鬓华发笑如月 靥如...
    泪花香阅读 270评论 0 1
  • 午加餐:西梅,麦片晚水果:香蕉,葡萄 参考目标: 1份肉2份豆制品3份“新鲜”水果4份谷物/薯5份蔬菜,深绿色叶菜...
    静趣_儿童心理师阅读 125评论 0 0
  • 转眼已进入凌晨快5点,儿子嗓子化痰、哭闹不睡,让时间显的尤其快,还好他这会已经安静的在我怀里入睡了,而我想用文字...
    e4fd0885435f阅读 352评论 0 2