Cocoa - NSMenuItem中的自定义NSView不会绘制

时间:2011-03-01 22:12:04

标签: cocoa nsview nsmenuitem

我有一个自定义的NSView,曾经在NIB中创建并被指定为NSMenuItem的视图,效果很好,但现在我想用代码创建视图(我有理由向你保证)看起来并不难,但视图实际上并没有画出来。

即使我发送“setNeedsDisplay:”消息,也不再调用以前被调用以在需要时绘制视图的“drawRect:”消息。

我使用图像初始化视图并设置(视图的大小与图像大小相匹配),这似乎有效,因为菜单项的大小合适,但没有图像。

这里可能会发生什么?

这是初始化视图的代码:

-(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 个答案:

答案 0 :(得分:1)

您必须先设置视图frame,然后才能设置其bounds。在您的-init...中,要么交换两个set...来电,要么删除setBounds:(默认情况下bounds默认设置为{(0,0), (frame.size.width, frame.size.height)}),一切都应该有效。我也认为您不需要在frame中再次设置boundsdrawRect,事实上,当焦点已经锁定在您的视图上时,更改这些内容似乎是一个坏主意;如果值实际上不同,它最多会导致奇怪的闪烁。

更新:刚刚在View Programming Guide

中看到了这个说明
  

注意:应用程序使用任何setBounds ...方法显式设置视图的边界矩形后,更改视图的框架矩形不再自动更改边界矩形。有关详细信息,请参阅“Repositioning and Resizing Views”。