您好,欢迎来到二三娱乐。
搜索
您的当前位置:首页NSButton设置字体颜色

NSButton设置字体颜色

来源:二三娱乐

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

Copyright © 2019- yule263.com 版权所有 湘ICP备2023023988号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务