子类NSView来改变背景颜色 [英] Subclass NSView to change background color
问题描述
我想更改自定义视图的背景颜色。我有一个子类NSView像这样:
I want to change the background color of a custom view. I have a subclass NSView something like that:
#import <Cocoa/Cocoa.h>
@interface CustomBGView : NSView {
NSColor myColor;
} @end
和.m
@implementation CustomBGView
- (void)drawRect:(NSRect)rect
{
[myColor set];
NSRectFill([self bounds]);
}
- (void)changeColor:(NSColor*) aColor
{
myColor = aColor;
}
changeColor方法用于在应用程序控制器中更改颜色。我还为自定义视图定义了一个IBOutlet,在IB中称为myView binded。
The changeColor method is for change color in the app controller. I also define a IBOutlet for the custom view called myView binded in IB.
问题是当我在应用控制器中使用changeColor时:
The problem is when I use changeColor in the app controller like this:
[myView changeColor: [NSColor colorWithCalibratedRed:0.5 green:0.5 blue:0.5 alpha:1.0]];
有一个程序接收信号:EXC_BAD_ACCESS。如果我改用这样的东西:
There is a 'Program received signal: "EXC_BAD_ACCESS". If I use instead something like this:
[myView changeColor: [NSColor whiteColor]];
可以正常工作。
问题在哪里?提前感谢
谢谢Chuck!现在用retain工作正常。
Thanks Chuck! Now with "retain" works fine.
为什么它在一个案例中没有保留([myView changeColor:[NSColor whiteColor]];)而不在其他???
And why it works without retain in one case ([myView changeColor: [NSColor whiteColor]];) and not in the other???
推荐答案
您在实例变量中存储了 changeColor:
的参数, ,所以你不拥有它,它认为它可以消失。
You're storing the argument to changeColor:
in an instance variable, but not retaining it, so you don't own it and it thinks it can go away.
这篇关于子类NSView来改变背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!