I'm working on my first Swift project (hooray), which is an app for Mac OS. What I want to do now is create some buttons, with a white text color and a custom font. Because I needed a new attribute on that button to hold some data, I made a child class of NSButton
.
Now, I know that I can set the font of a button like this:
super.font = NSFont(name: "NB-International-Pro", size: 40)
Which worked like a charm. After that I tried to change the color of the text by doing this:
let pstyle = NSMutableParagraphStyle()
pstyle.alignment = .center
super.attributedTitle = NSAttributedString(string: (device?.name)!, attributes: [ NSForegroundColorAttributeName : NSColor.white, NSParagraphStyleAttributeName : pstyle ])
Which did work, and it did change the color of the text, however, now the font and font size are back to default. Is there an option to do both?
Thanks.
Instead of setting the font first, include the font name and size in your attributes when creating your NSAttributedString
by using the NSFontAttributeName
and NSFontSizeAttribute
keys:
attributedTitle = NSAttributedString(string: (device?.name)!, attributes: [ NSForegroundColorAttributeName : NSColor.white, NSParagraphStyleAttributeName : pstyle, NSFontAttributeName: "NB-International-Pro", NSFontSizeAttribute: 40])
Beyond that there's probably some improvements you can make to the architecture of your code. Subclassing NSButton
is not really needed just for changing text style (can be done either in .xib or your view controller).