2015-01-10 11 views
7

Ich würde gerne wissen, wie Titelfarbe zu einem NSButton in swift ändern, ich habe viele Beispiele in objective-c gesehen, aber ich denke in schnell die Umsetzung ist anders, kann mir jemand zur Verfügung stellen ein Beispiel?Swift Mac OSX NSButton Titelfarbe

Antwort

19

versuchen Sie dies in viewDidLoad oder irgendwo.

In Swift 3:

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

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

Danke mann du hast meinen Tag !!! – PhiceDev

+3

In Swift 2 müssen Sie '.CenterTextAlignment' ändern' .Center' – Sebastian

+3

Swift 3-Version: 'lassen paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = .center button.attributedTitle = NSAttributedString (string: "Titel", Attribute: [NSForegroundColorAttributeName: NSColor.red, NSParagraphStyleAttributeName: paragraphStyle]) ' –

0

In Swift4

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

Xcode 9 mit Swift 4 ist noch nicht out und ist auch nicht GM. Also, das ändert sich vielleicht nicht, ich denke, du springst hier – Chris

1

Swift 4

ich dies als eine zusätzliche Antwort hinzugefügt haben, da sie nur die angeforderte Attribut ändert, ohne zu überschreiben oder zusätzliche hinzufügen.

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