macOS编程 NSView改变背景色

来源:互联网 发布:揭阳淘宝村在哪里 编辑:程序博客网 时间:2024/06/05 14:28

和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






原创粉丝点击