我有一个名为“testClass”的自定义NSView类。我在我的主应用程序控制器类中创建了这个类的实例。 testClass包含一个4元素的float数组作为实例变量,它保存NSView背景的颜色。我想从主控制器类设置这些值,然后drawRect:应该使用它们来绘制背景。但是,当我设置值时,drawRect拒绝查看它们。他们总是0.0。
在Interface Builder中,我将自定义视图放在应用程序MainMenu.xib的主窗口中。然后我将它分配给testClass。
这是我的代码:
@interface testClass : NSView
{
@public
float colors[4];
}
@end
@implementation testClass
-(void)drawRect:(NSRect)dirtyRect
{
//The colors are ALWAYS 0.0, 0.0, 0.0:
fprintf(stderr,"colors: %.2f %.2f %.2f\n",colors[0],colors[1],colors[2]);
NSColor *c = [NSColor colorWithCalibratedRed:colors[0] green:colors[1] blue:colors[2] alpha:1.0];
[c setFill];
NSRectFill(dirtyRect);
}
@end
//Now, in the main app controller:
testClass *test = [[testClass alloc] init];
test->colors[0] = 1.00; //r
test->colors[1] = 0.75; //g
test->colors[2] = 0.25; //b
test->colors[3] = 1.00; //a
[test setNeedsDisplay:YES];
//This prints the colors as they should be:
fprintf(stderr,"colors: %.2f %.2f %.2f\n",
test->colors[0],
test->colors[1],
test->colors[2]);
为什么自定义视图无法识别自己的变量,即使我从创建自定义类的类中调用setNeedsDisplay:YES?如果我要做的事情不起作用,那么正确的做法是什么?
更新
正如user1118321指出的那样,用[[testClass alloc] init]行创建的testClass的实例不是我应该做的。由于我在Interface Builder中已经有一个自定义视图形式的testClass实例(我指定了“testClass”),我只需要在主控制器类中创建一个指向它的指针作为IBOutlet。一旦我做到了,它就有效了!