NSButton如何为文本着色

时间:2012-10-28 15:05:53

标签: objective-c macos nsbutton textcolor

OSX上的

我有一个非常暗的图像的NSButton,不幸的是,使用属性检查器无法更改颜色。看图片大黑色按钮,文字 Go

enter image description here

是否有可能改变文字颜色的线索?我查看了NSButton类,但没有方法可以做到这一点。我知道我可以使用白色字体制作图像,但这不是我想要做的。

来自瑞士的问候,罗纳德霍夫曼 ---

13 个答案:

答案 0 :(得分:43)

这是另外两个解决方案: <击> http://denis-druz.okis.ru/news.534557.Text-Color-in-NSButton.html

解决方案1:

-(void)awakeFromNib
{
    NSColor *color = [NSColor greenColor];
    NSMutableAttributedString *colorTitle = [[NSMutableAttributedString alloc] initWithAttributedString:[button attributedTitle]];
    NSRange titleRange = NSMakeRange(0, [colorTitle length]);
    [colorTitle addAttribute:NSForegroundColorAttributeName value:color range:titleRange];
    [button setAttributedTitle:colorTitle];
}

解决方案2:

<。>文件中的

- (void)setButtonTitleFor:(NSButton*)button toString:(NSString*)title withColor:(NSColor*)color
{
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    [style setAlignment:NSCenterTextAlignment];
    NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:color, NSForegroundColorAttributeName, style, NSParagraphStyleAttributeName, nil];
    NSAttributedString *attrString = [[NSAttributedString alloc]initWithString:title attributes:attrsDictionary];
    [button setAttributedTitle:attrString];
}

-(void)awakeFromNib
{
    NSString *title = @"+Add page";
    NSColor *color = [NSColor greenColor];
    [self setButtonTitleFor:button toString:title withColor:color];
}

答案 1 :(得分:13)

我的解决方案:

.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

这是一个Swift 3版本:

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

}

和Swift 4.0版本:

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

答案 2 :(得分:7)

Apple有代码将NSButton的文本颜色设置为Popover example的一部分。

以下是该示例的关键(此帖子略有修改,未经测试):

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

请注意,对fixAttributesInRange:的调用似乎很重要(AppKit扩展名),但我找不到关于为什么的文档。我在NSButton中使用属性字符串的唯一问题是,如果还为按钮定义了图像(例如图标),则属性字符串将占据一个大矩形并将图像推到按钮的边缘。要记住的事情。

否则,最好的办法似乎是制作你自己的drawRect:覆盖,这有很多其他缺陷超出了这个问题的范围。

答案 3 :(得分:5)

这就是我在Swift 4中完成它的方法

 @IBOutlet weak var myButton: NSButton!

 // create the attributed string
 let myString = "My Button Title"
 let myAttribute = [ NSAttributedStringKey.foregroundColor: NSColor.blue ]
 let myAttrString = NSAttributedString(string: myString, attributes: myAttribute)
 // assign it to the button
 myButton.attributedTitle = myAttrString

答案 4 :(得分:4)

我创建了一个名为NSButton的{​​{1}}子类,可以让您轻松更改Interface Builder的Attributes Inspector中的文本颜色,就像您要求的那样。它应该为您的问题提供简单而广泛的解决方案。

它还会公开其他相关的样式属性,例如颜色和形状。

您可以在此处找到它:https://github.com/OskarGroth/FlatButton

FlatButton for macOS

答案 5 :(得分:3)

在NSButton上添加一个类别,只需将颜色设置为您想要的颜色,并预先设置现有属性,因为标题可以居中,左对齐等等。


@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

答案 6 :(得分:2)

一个非常简单,可重用的解决方案,没有子类化NSButton:

[self setButton:self.myButton fontColor:[NSColor whiteColor]] ;

-(void) setButton:(NSButton *)button fontColor:(NSColor *)color {
    NSMutableAttributedString *colorTitle = [[NSMutableAttributedString alloc] initWithAttributedString:[button attributedTitle]];
    [colorTitle addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0, button.attributedTitle.length)];
    [button setAttributedTitle:colorTitle];
}

答案 7 :(得分:1)

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;  

答案 8 :(得分:1)

快捷键5

您可以使用此扩展名:

extension NSButton {

@IBInspectable var titleColor: NSColor? {
    get {
        return   NSColor.white
    }
    set {
        let pstyle = NSMutableParagraphStyle()
        pstyle.alignment = .center
        
        self.attributedTitle = NSAttributedString(
            string: self.title,
            attributes: [ NSAttributedString.Key.foregroundColor :newValue, NSAttributedString.Key.paragraphStyle: pstyle])
        
    }
   }
 }

现在,您可以轻松在情节提要中设置标题颜色。干杯!

答案 9 :(得分:1)

如果部署目标> 10.14,则可以使用contentTintColor设定颜色。

/** Applies a tint color to template image and text content, in combination with other theme-appropriate effects. Only applicable to borderless buttons. A nil value indicates the standard set of effects without color modification. The default value is nil. Non-template images and attributed string values are not affected by the contentTintColor. */
@available(macOS 10.14, *)
@NSCopying open var contentTintColor: NSColor?

示例代码:

var confirmBtn = NSButton()
confirmBtn.title = "color"
confirmBtn.contentTintColor = NSColor.red

答案 10 :(得分:0)

使用上面的信息,我编写了一个NSButton扩展,它设置了前景色,以及系统字体和文本对齐方式。

这适用于Swift 4.x上的Cocoa,但可以很容易地针对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
    }
}

答案 11 :(得分:0)

当目标是macOS 10.14或更高版本时,可以使用NSButton控件的新tintColor属性来设置文本颜色。

答案 12 :(得分:0)

David Boyd解决方案的Swift 4.2版本

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

    var attributes: [NSAttributedString.Key: Any] = [:]

    if let foreground = foreground {
        attributes[NSAttributedString.Key.foregroundColor] = foreground
    }

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

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

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

}