我有一个自定义的NSView,它曾经在NIB中创建并作为NSMenuItem的视图分配,这非常棒,但现在我想在代码中创建视图我可以向你保证的好理由)哪个看起来不难,但是这个看法实际上并没有绘制。可可 - NSMenuItem中的自定义NSView不会绘制
即使在发送“setNeedsDisplay:”消息时,以前被调用以在需要时绘制视图的“drawRect:”消息不再被调用。
我用图像初始化视图,并设置大小(与图像大小相匹配的视图),因为菜单项大小正确,但没有图像,所以似乎可行。
这里可能会发生什么?
这是给init视图代码:
-(id)initWithImage:(NSImage*)image
{
self = [super init];
if (self != nil)
{
self.imageToDisplay = image;
// this bit does get called and resizes the view to match the image size
NSRect imageBounds = NSMakeRect(0.0f, 0.0f, imageToDisplay.size.width, imageToDisplay.size.height);
[self setBounds:imageBounds];
[self setFrame:imageBounds];
[self setHidden:NO];
[self setAlphaValue:1.0f];
[self setAutoresizesSubviews:YES];
}
return self;
}
这是绘制不被调用
// this is never called
-(void)drawRect:(NSRect)dirtyRect
{
if (imageToDisplay == nil)
return;
NSRect imageBounds = NSMakeRect(0.0f, 0.0f, imageToDisplay.size.width, imageToDisplay.size.height);
[self setBounds:imageBounds];
[self setFrame:imageBounds];
[imageToDisplay drawInRect:[self bounds]
fromRect:imageBounds
operation:NSCompositeSourceAtop
fraction:1.0f];
}
视图代码这是菜单项的代码它增加了视图。
-(void)awakeFromNib
{
MyCustomView* view = [[MyCustomView alloc] init];
[self setView:view];
// i would have expected the image to get drawn at this point
[view setNeedsDisplay:YES];
}
现货!非常感谢:) – Nippysaurus 2011-03-13 09:54:36
很高兴我能帮忙。 – 2011-03-13 22:32:11