Swift Mac OSX NSButton title color

血红的双手。 提交于 2019-12-19 17:42:30

问题


I would like to know how to change title color to a NSButton in swift, I've seen lots of examples in objective-c but I think in swift the implementation is different, can anyone provide me an example?


回答1:


try this in viewDidLoad or somewhere.

In Swift 3:

    let pstyle = NSMutableParagraphStyle()
    pstyle.alignment = .center

    button.attributedTitle = NSAttributedString(string: "Title", attributes: [ NSForegroundColorAttributeName : NSColor.red, NSParagraphStyleAttributeName : pstyle ])



回答2:


Swift 4

I've added this as an additional answer since it changes only the requested attribute without overwriting or adding additional ones.

if let mutableAttributedTitle = button.attributedTitle.mutableCopy() as? NSMutableAttributedString {
    mutableAttributedTitle.addAttribute(.foregroundColor, value: NSColor.white, range: NSRange(location: 0, length: mutableAttributedTitle.length))
    button.attributedTitle = mutableAttributedTitle
}



回答3:


In Swift4

button.attributedTitle = NSMutableAttributedString(string: "Hello World", attributes: [NSAttributedStringKey.foregroundColor: NSColor.white, NSAttributedStringKey.paragraphStyle: style, NSAttributedStringKey.font: NSFont.systemFont(ofSize: 18)])


来源:https://stackoverflow.com/questions/27875813/swift-mac-osx-nsbutton-title-color

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!