将背景颜色设置为 NSView
我想念什么?颜色不会改变。
#import "controller.h"
#import "backgroundView.h"
@implementation controller
-(void)awakeFromNib {
backgroundView *background = [[backgroundView alloc] init];
[background setBackgroudColor:[NSColor whiteColor]];
//also didn't work
//[background setBackgroudColor:[[NSColor whiteColor] retain]];
}
@end
//backgroundView.h
#import <Cocoa/Cocoa.h>
@interface backgroundView : NSView{
NSColor *color;
}
-(void)setBackgroudColor:(NSColor*)newColor;
@end
#import "backgroundView.h"
@implementation backgroundView
-(void)dealloc{
[super dealloc];
}
-(void)setBackgroudColor:(NSColor*)newColor{
color = newColor;
[self setNeedsDisplay:YES];
}
-(void)drawRect:(NSRect)rect{
[color setFill];
NSRectFill(rect);
}
@end
What I miss? color won't change.
#import "controller.h"
#import "backgroundView.h"
@implementation controller
-(void)awakeFromNib {
backgroundView *background = [[backgroundView alloc] init];
[background setBackgroudColor:[NSColor whiteColor]];
//also didn't work
//[background setBackgroudColor:[[NSColor whiteColor] retain]];
}
@end
//backgroundView.h
#import <Cocoa/Cocoa.h>
@interface backgroundView : NSView{
NSColor *color;
}
-(void)setBackgroudColor:(NSColor*)newColor;
@end
#import "backgroundView.h"
@implementation backgroundView
-(void)dealloc{
[super dealloc];
}
-(void)setBackgroudColor:(NSColor*)newColor{
color = newColor;
[self setNeedsDisplay:YES];
}
-(void)drawRect:(NSRect)rect{
[color setFill];
NSRectFill(rect);
}
@end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
setBackgroundColor:
方法中保留newColor
。dealloc
中释放color
ivarinit
初始化视图,但指定的初始化程序是initWithFrame:
NSColor
使用set
而不是setFill
newColor
insetBackgroundColor:
method.color
ivar indealloc
init
, but designated initializer isinitWithFrame:
set
instead ofsetFill
forNSColor
您正在
awakeFromNib
中创建一个视图,该视图附加到任何地方。相反,您应该在 Interface Builder 中更改视图的自定义类,在此视图上设置一个插座并对其调用setBackgroudColor:
。另外,类应该以大写字母开头,因此
backgroundView
应该是BackgroundView
。正如 Andriy 所说,请确保修复color
ivar 的内存管理。You are creating a view in
awakeFromNib
which is attached to nowhere. Instead you should change the custom class of your view in Interface Builder, setup an outlet on this view and callsetBackgroudColor:
on it.Also, classes should start with a capital letter so
backgroundView
should beBackgroundView
. As Andriy said, make sure to fix the memory management of yourcolor
ivar.