In this era of white-on-black (HUD) interfaces, we often want to change the text-color of NSButtons (including checkboxes and such). NSTextFieldCell has a -setTextColor: method, but NSButtonCell doesn’t. You can use -setAttributedTitle: to achieve the desired result, but that’s a bit of a hassle.
Here’s a simple little category on NSButton which adds -textColor and -setTextColor: methods to the class.
Header:
@interface NSButton (TextColor)
- (NSColor *)textColor;
- (void)setTextColor:(NSColor *)textColor;
@end
Implementation:
@implementation NSButton (TextColor)
- (NSColor *)textColor
{
NSAttributedString *attrTitle = [self attributedTitle];
int len = [attrTitle length];
NSRange range = NSMakeRange(0, MIN(len, 1)); // take color from first char
NSDictionary *attrs = [attrTitle fontAttributesInRange:range];
NSColor *textColor = [NSColor controlTextColor];
if (attrs) {
textColor = [attrs objectForKey:NSForegroundColorAttributeName];
}
return textColor;
}
- (void)setTextColor:(NSColor *)textColor
{
NSMutableAttributedString *attrTitle = [[NSMutableAttributedString alloc]
initWithAttributedString:[self attributedTitle]];
int len = [attrTitle length];
NSRange range = NSMakeRange(0, len);
[attrTitle addAttribute:NSForegroundColorAttributeName
value:textColor
range:range];
[attrTitle fixAttributesInRange:range];
[self setAttributedTitle:attrTitle];
[attrTitle release];
}
@end
Tomonaga Tokuyama Enterprises | 10-Jan-08 at 3:59 pm | Permalink
[NSValueTransformer] StringAttributes…
Again, Matt Legend Gemmell introduces Setting the text color of an NSButton. I made its NSValueTransformer subclass version, which works with Cocoa Bindings.
Header,
#import <Cocoa/Cocoa.h>
@interface TTStringAttributesValueTransformer : …