OK, long story short:
NSButton
sNSButton
subclass I want to colour them, exactly the way the Xcode tab items are colouredThis is how I'm setting the color (as a simple NSColor):
NSColor *color = [NSColor colorWithCalibratedRed:0.09 green:0.55 blue:0.90 alpha:1.0];
NSMutableAttributedString *colorTitle =
[[NSMutableAttributedString alloc] initWithAttributedString:[self attributedTitle]];
NSRange titleRange = NSMakeRange(0, [colorTitle length]);
[colorTitle addAttribute:NSForegroundColorAttributeName
value:color
range:titleRange];
[self setAttributedTitle:colorTitle];
How can I set it to an NSGradient
?
OK, here's the solution, for anyone who may find useful...
Step 1:
Create a category on NSColor
, based on the great answer by @Omz. In the code below, you'll see it renamed as colorFromGradient:
, solely in order to mix well with the usual Cocoa naming conventions...
Step 2:
Redraw the title with the gradient color
NSColor* gS = [NSColor colorWithCalibratedRed:0.07 green:0.47 blue:0.87 alpha:1.0];
NSColor* gE = [NSColor colorWithCalibratedRed:0.12 green:0.64 blue:0.94 alpha:1.0];
NSGradient* g = [[NSGradient alloc] initWithStartingColor:gE endingColor:gS];
NSColor *color = [NSColor colorFromGradient:g];
NSMutableAttributedString *colorTitle =
[[NSMutableAttributedString alloc] initWithAttributedString:[self attributedTitle]];
NSRange titleRange = NSMakeRange(0, [colorTitle length]);
[colorTitle addAttribute:NSForegroundColorAttributeName
value:color
range:titleRange];
[self setAttributedTitle:colorTitle];
Step 3:
Enjoy the result. :-)