My solution:
.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
And here’s a Swift 3 version:
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)
}
}
and Swift 4.0 version:
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)
}
}
- [NSMutableAttributedString addAttribute:NSForegroundColorAttributeName value:[NSColor colorWithSRGBRed:1.0 green:0.0 blue:0.0 alpha:0.0] range:NSMakeRange(0, string.length)];
– Potoroo