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, the text is Go.
Any clues for a possibility to change the text color? I looked in to the NSButton class but there is no method to do that. I´m aware that I could make the image with white font but that is not what I want to do.
Greetings from Switzerland, Ronald Hofmann ---
I've created a
NSButton
subclass calledFlatButton
that makes it super-easy to change the text color in the Attributes Inspector of Interface Builder like you are asking for. It should provide a simple and extensive solution to your problem.It also exposes other relevant styling attributes such as color and shape.
You'll find it here: https://github.com/OskarGroth/FlatButton
Add a category on the NSButton and simply set the color to what you want, and preseve the existing attributes, since the title can be centered, left aligned etc
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.
My solution:
And here’s a Swift 3 version:
and Swift 4.0 version:
Apple have code for setting the text colour of an NSButton as part of the Popover example.
Below is the crux of the example (modified slightly for this post, untested):
Note that the call to
fixAttributesInRange:
seems to be important (an AppKit extension), but I can't find documentation as to why that is the case. The only concern I have with using attributed strings in an NSButton is if an image is also defined for the button (such as an icon), the attributed string will occupy a large rectangle and push the image to the edge of the button. Something to bear in mind.Otherwise it seems the best way is to make your own
drawRect:
override instead, which has many other pitfalls that are outside the scope of this question.