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
{
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];
}