NSButton how to color the text

后端 未结 12 1519
伪装坚强ぢ
伪装坚强ぢ 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

    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.

提交回复
热议问题