Cocoa - Custom NSView in NSMenuItem will not draw
I have a custom NSView which used to get created in a NIB and assigned as the view for an NSMenuItem, which works great, but now I want to create the view in code (for good reason I can assure you) which did not look hard but but the view is not actually drawing.
The "drawRect:" message which was previously being called to draw the view when required is not being called anymore even when I send a "setNeedsDisplay:" message.
I init the view with an image and set the size (of the view to match the image size) which seems to work because the menu item is the right size, but there is no image.
What could be happening here?
This is the code to init the view:
-(id)initWithImage:(NSImage*)image
{开发者_JAVA百科
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;
}
And this is the code for drawing the view which does not get called
// 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];
}
And this is the code for the menu item which adds the view.
-(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];
}
You have to set your view's frame
before you can set its bounds
. In your -init...
, either swap the two set...
calls, or remove the setBounds:
(bounds
is set to {(0,0), (frame.size.width, frame.size.height)}
by default anyways) and everything should work. I also don't think that you need to set frame
and bounds
again in drawRect
, and in fact it seems like a bad idea to change those when focus is already locked on your view; at best it will cause weird flashing if the values are actually different.
UPDATE: just saw this note in the View Programming Guide:
Note: Once an application explicitly sets the bounds rectangle of a view using any of the setBounds... methods, altering the view's frame rectangle no longer automatically changes the bounds rectangle. See "Repositioning and Resizing Views" for details.
精彩评论