macos 设置 NSView 的背景颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7541183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting the background color of an NSView
提问by pmerino
I want to set a custom view (not the main one) with a custom NSColor background ([NSColor colorWithPatternImage:[NSImage imageNamed:@"pattern.png"]]
). I've tried making a custom view class:
我想设置一个带有自定义 NSColor 背景 ( [NSColor colorWithPatternImage:[NSImage imageNamed:@"pattern.png"]]
)的自定义视图(不是主要视图)。我试过制作自定义视图类:
.h
。H
#import <AppKit/AppKit.h>
@interface CustomBackground : NSView {
NSColor *background;
}
@property(retain) NSColor *background;
@end
.m
.m
#import "CustomBackground.h"
@implementation CustomBackground
@synthesize background;
- (void)drawRect:(NSRect)rect
{
[background set];
NSRectFill([self bounds]);
}
- (void)changeColor:(NSColor*) aColor
{
background = aColor;
[aColor retain];
}
@end
And then in the AppDelegate:
然后在 AppDelegate 中:
[self.homeView changeColor:[NSColor colorWithPatternImage:[NSImage imageNamed:@"pattern.png"]]];
But nothing happens, the color remains the same. What's wrong? Or is there an easier way? NSView doesn't have a backgroundColor
property :(
但没有任何反应,颜色保持不变。怎么了?或者有更简单的方法吗?NSView 没有backgroundColor
属性:(
回答by SMS
Try
尝试
[self.homeView setWantsLayer:YES];
self.homeView.layer.backgroundColor = [NSColor redColor].CGColor;
回答by Isabel
It's best to use the already-made setBackground:
method that you get from the background
property. So replace your changeColor:
method with:
最好使用setBackground:
您从background
属性中获得的已经制作的方法。因此,将您的changeColor:
方法替换为:
-(void)setBackground:(NSColor *)aColor
{
if([background isEqual:aColor]) return;
[background release];
background = [aColor retain];
//This is the most crucial thing you're missing: make the view redraw itself
[self setNeedsDisplay:YES];
}
To change the color of your view, you can simply do:
要更改视图的颜色,您只需执行以下操作:
self.homeView.background = [NSColor colorWithPatternImage:[NSImage imageNamed:@"pattern.png"]]