Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set the text color of an NSButton via Interface Builder?

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...

like image 806
Troy Avatar asked Oct 31 '22 07:10

Troy


2 Answers

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

like image 90
Ryan Francesconi Avatar answered Nov 14 '22 02:11

Ryan Francesconi


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];
like image 20
Gowtham Avatar answered Nov 14 '22 03:11

Gowtham