首先创建一个category 文件名为NSView+backgroundColor

NSView+backgroundColor.h

1
2
3
4
5
#import <Cocoa/Cocoa.h>

@interface NSView (OSXBGColorExtension)
@property (nonatomic, weak) NSColor *backgroundColor;
@end

NSView+backgroundColor.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#import "NSView+backgroundColor.h"

@implementation NSView (OSXBGColorExtension)
- (NSColor *) backgroundColor
{
CGColorRef colorRef = self.layer.backgroundColor;
NSColor *theColor = [NSColor colorWithCGColor:colorRef];
return theColor;
}

- (void) setBackgroundColor:(NSColor *)backgroundColor
{
[self setWantsLayer:YES];
self.layer.backgroundColor = backgroundColor.CGColor;
}
@end

然后在User Defined Runtime Attributes里面直接设置颜色 key为backgroundColor

这种方法比在drawrect里面改颜色要好多了,IB中或者代码都可以使用,一个操作或者一句话搞定