NSButton how to color the text

后端 未结 12 1524
伪装坚强ぢ
伪装坚强ぢ 2020-12-13 00:35

on OSX I have an NSButton with a pretty dark image and unfortunately it is not possible to change the color using the attributes inspector. See picture the big black button,

12条回答
  •  鱼传尺愫
    2020-12-13 01:09

    Using the info above, I wrote a NSButton extension that sets the foreground color, along with the system font and text alignment.

    This is for Cocoa on Swift 4.x, but could be easily adjusted for iOS.

    import Cocoa
    
    extension NSButton {
        func setAttributes(foreground: NSColor? = nil, fontSize: CGFloat = -1.0, alignment: NSTextAlignment? = nil) {
    
            var attributes: [NSAttributedStringKey: Any] = [:]
    
            if let foreground = foreground {
                attributes[NSAttributedStringKey.foregroundColor] = foreground
            }
    
            if fontSize != -1 {
                attributes[NSAttributedStringKey.font] = NSFont.systemFont(ofSize: fontSize)
            }
    
            if let alignment = alignment {
                let paragraph = NSMutableParagraphStyle()
                paragraph.alignment = alignment
                attributes[NSAttributedStringKey.paragraphStyle] = paragraph
            }
    
            let attributed = NSAttributedString(string: self.title, attributes: attributes)
            self.attributedTitle = attributed
        }
    }
    

提交回复
热议问题