和UIView不同, NSView不能直接通过backgroundColor改变背景色
这里总结下NSView用代码改变背景色的两种方法:
第一种:
不自定义子类,直接在layer上改变背景色
NSView *view = [[NSView alloc]init];
view.frame = NSMakeRect(0, 0, 100, 100);
view.wantsLayer = YES;
view.layer.backgroundColor = [NSColor redColor].CGColor;
[self.view addSubview:view];
第二种:
自定义子类,在drawRect方法中改变背景色
- (void)drawRect:(NSRect)dirtyRect {
[[NSColor yellowColor] setFill];
NSRectFill(dirtyRect);
[super drawRect:dirtyRect];
}
资料参考来源:
https://stackoverflow.com/questions/2962790/best-way-to-change-the-background-color-for-an-nsview