2011-03-01 41 views
3

我有一个自定义的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]; 
} 

回答

1

你必须设置你的视图的frame你可以设置它的bounds之前。在你的-init...中,要么调用两个set...调用,要么删除setBounds:(默认情况下,bounds被设置为{(0,0), (frame.size.width, frame.size.height)}),一切都应该工作。我也不认为你需要在drawRect中再次设置framebounds,事实上,当焦点已经锁定在视图上时,改变这些似乎不是个好主意;如果这些值实际上不同,最好会造成奇怪的闪烁。

更新:刚才看到这个便条在View Programming Guide

注意:一旦应用程序明确设置使用任何的setBounds ...方法视图的边界矩形,改变视图的框架矩形不再自动更改边界矩形。详情请参阅“Repositioning and Resizing Views”。

+0

现货!非常感谢:) – Nippysaurus 2011-03-13 09:54:36

+0

很高兴我能帮忙。 – 2011-03-13 22:32:11

相关问题