NSButton how to color the text

后端 未结 12 1517
伪装坚强ぢ
伪装坚强ぢ 2020-12-13 00:35

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,

12条回答
  •  时光取名叫无心
    2020-12-13 01:11

    Here is two other solutions: http://denis-druz.okis.ru/news.534557.Text-Color-in-NSButton.html

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

    solution 2:

    in *.m file:

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

提交回复
热议问题