5
votes

There are several questions about how to set the text color programmatically. That's all fine, but there's got to be a way to do it via Interface Builder also.

The "Show Fonts" box works for changing the size of the button text, but Xcode ignores any color changes made using the widget there, and the Attributes Inspector for NSButton doesn't have a color picker...

4

4 Answers

5
votes

I've no idea why this is missing still from NSButton. But here is the replacement class in Swift 4:

import Cocoa

class TextButton: NSButton {
    @IBInspectable open var textColor: NSColor = NSColor.black
    @IBInspectable open var textSize: CGFloat = 10

    public override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
    }

    public required init?(coder: NSCoder) {
        super.init(coder: coder)
    }

    override func awakeFromNib() {
        let titleParagraphStyle = NSMutableParagraphStyle()
        titleParagraphStyle.alignment = alignment

        let attributes: [NSAttributedStringKey : Any] = [.foregroundColor: textColor, .font: NSFont.systemFont(ofSize: textSize), .paragraphStyle: titleParagraphStyle]
        self.attributedTitle = NSMutableAttributedString(string: self.title, attributes: attributes)
    }
}

enter image description here

enter image description here

1
votes

Try this solution,i hope so you will get :)

NSFont *txtFont = button.font;
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
[style setAlignment:button.alignment];
NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                     [NSColor whiteColor], NSForegroundColorAttributeName, style, NSParagraphStyleAttributeName, txtFont, NSFontAttributeName, nil];
NSAttributedString *attrString = [[NSAttributedString alloc]
                                      initWithString:button.title attributes:attrsDictionary];
[button setAttributedTitle:attrString];
0
votes

You can also add this extension to your code if you like the 'Throw an extension in and look if it sticks' approach.

extension NSButton {

  @IBInspectable open var textColor: NSColor? {
    get {
      return self.attributedTitle.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? NSColor
    }
    set {
      var attributes = self.attributedTitle.attributes(at: 0, effectiveRange: nil)
      attributes[.foregroundColor] = newValue ?? NSColor.black
      self.attributedTitle = NSMutableAttributedString(string: self.title,
                                                       attributes: attributes)
    }
  }
}
-4
votes

Edit: Misread question. Below is how you'd change the text of a button on an iOS app.

Just to clarify, this isn't working for you?

  • added button
  • click on it and go to Attributes Inspector
  • change color in "Text Color" field

Changed button color to reddish