NSButton how to color the text

2019-01-21 17:06发布

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.

enter image description here

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

10条回答
我欲成王,谁敢阻挡
2楼-- · 2019-01-21 17:16

I've created a NSButton subclass called FlatButton 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

FlatButton for macOS

查看更多
爷的心禁止访问
3楼-- · 2019-01-21 17:18

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


@implementation NSButton (NSButton_IDDAppKit)

- (NSColor*)titleTextColor {

    return [NSColor redColor];

}

- (void)setTitleTextColor:(NSColor*)aColor {

    NSMutableAttributedString*  attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedTitle];
    NSString*  title = self.title;
    NSRange  range = NSMakeRange(0.0, self.title.length);

    [attributedString addAttribute:NSForegroundColorAttributeName value:aColor range:range];
    [self setAttributedTitle:attributedString];
    [attributedString release];

}

@end
查看更多
神经病院院长
4楼-- · 2019-01-21 17:21

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.

import Cocoa

extension NSButton {
    func setAttributes(foreground: NSColor? = nil, fontSize: CGFloat = -1.0, alignment: NSTextAlignment? = nil) {

        var attributes: [NSAttributedStringKey: Any] = [:]

        if let foreground = foreground {
            attributes[NSAttributedStringKey.foregroundColor] = foreground
        }

        if fontSize != -1 {
            attributes[NSAttributedStringKey.font] = NSFont.systemFont(ofSize: fontSize)
        }

        if let alignment = alignment {
            let paragraph = NSMutableParagraphStyle()
            paragraph.alignment = alignment
            attributes[NSAttributedStringKey.paragraphStyle] = paragraph
        }

        let attributed = NSAttributedString(string: self.title, attributes: attributes)
        self.attributedTitle = attributed
    }
}
查看更多
放我归山
5楼-- · 2019-01-21 17:22

My solution:

.h

IB_DESIGNABLE
@interface DVButton : NSButton

@property (nonatomic, strong) IBInspectable NSColor *BGColor;
@property (nonatomic, strong) IBInspectable NSColor *TextColor;

@end


.m

@implementation DVButton

- (void)awakeFromNib
{
    if (self.TextColor)
    {
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        [style setAlignment:NSCenterTextAlignment];
        NSDictionary *attrsDictionary  = [NSDictionary dictionaryWithObjectsAndKeys:
                                          self.TextColor, NSForegroundColorAttributeName,
                                          self.font, NSFontAttributeName,
                                          style, NSParagraphStyleAttributeName, nil];
        NSAttributedString *attrString = [[NSAttributedString alloc]initWithString:self.title attributes:attrsDictionary];
        [self setAttributedTitle:attrString];
    }
}


- (void)drawRect:(NSRect)dirtyRect
{
    if (self.BGColor)
    {
        // add a background colour
        [self.BGColor setFill];
        NSRectFill(dirtyRect);
    }

    [super drawRect:dirtyRect];
}

@end

enter image description here

And here’s a Swift 3 version:

import Cocoa

@IBDesignable
class DVButton: NSButton
{
    @IBInspectable var bgColor: NSColor?
    @IBInspectable var textColor: NSColor?

    override func awakeFromNib()
    {
        if let textColor = textColor, let font = font
        {
            let style = NSMutableParagraphStyle()
            style.alignment = .center

            let attributes =
            [
                NSForegroundColorAttributeName: textColor,
                NSFontAttributeName: font,
                NSParagraphStyleAttributeName: style
            ] as [String : Any]

            let attributedTitle = NSAttributedString(string: title, attributes: attributes)
            self.attributedTitle = attributedTitle
        }
    }

    override func draw(_ dirtyRect: NSRect)
    {
        if let bgColor = bgColor
        {
            bgColor.setFill()
            NSRectFill(dirtyRect)
        }

        super.draw(dirtyRect)
    }

}

and Swift 4.0 version:

import Cocoa

@IBDesignable
 class Button: NSButton
{
    @IBInspectable var bgColor: NSColor?
    @IBInspectable var textColor: NSColor?

    override func awakeFromNib()
    {
        if let textColor = textColor, let font = font
        {
            let style = NSMutableParagraphStyle()
            style.alignment = .center

            let attributes =
            [
                NSAttributedStringKey.foregroundColor: textColor,
                NSAttributedStringKey.font: font,
                NSAttributedStringKey.paragraphStyle: style
             ] as [NSAttributedStringKey : Any]

            let attributedTitle = NSAttributedString(string: title, attributes: attributes)
            self.attributedTitle = attributedTitle
        }
    }

    override func draw(_ dirtyRect: NSRect)
    {
        if let bgColor = bgColor
        {
            bgColor.setFill()
            __NSRectFill(dirtyRect)
        }

        super.draw(dirtyRect)
    }
}
查看更多
何必那么认真
6楼-- · 2019-01-21 17:27

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):

NSButton *button = ...;
NSMutableAttributedString *attrTitle =
    [[NSMutableAttributedString alloc] initWithString:@"Make Me Red"];
NSUInteger len = [attrTitle length];
NSRange range = NSMakeRange(0, len);
[attrTitle addAttribute:NSForegroundColorAttributeName value:[NSColor redColor] range:range];
[attrTitle fixAttributesInRange:range];
[button setAttributedTitle:attrTitle];

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.

查看更多
太酷不给撩
7楼-- · 2019-01-21 17:28
NSColor color = NSColor.White;  
NSMutableAttributedString colorTitle = new NSMutableAttributedString (cb.Cell.Title);                
NSRange titleRange = new NSRange (0, (nint)cb.Cell.Title.Length);
colorTitle.AddAttribute (NSStringAttributeKey.ForegroundColor, color, titleRange);      
cb.Cell.AttributedTitle = colorTitle;  
查看更多
登录 后发表回答