Cocoa - Custom NSView in NSMenuItem will not draw

I have a custom NSView that was used to create in NIB and assigned as a view for NSMenuItem, which works fine, but now I want to create a view in code (for good reason, I can assure you) that don't look heavy, but the view itself business is not drawn.

The "drawRect:" message that was previously called to draw the view as needed is no longer called even when I send the message "setNeedsDisplay:".

I start the view with the image and set the size (the view corresponding to the size of the image), which seems to work because the menu item has the right size, but there is no image.

What could be here?

This is the code to run 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;
}

,

// 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];
}
+3
1

frame, bounds. -init... set..., setBounds: (bounds {(0,0), (frame.size.width, frame.size.height)}), . , frame bounds drawRect, , ; , .

UPDATE: :

. setBounds..., . . "" ".

+1

Source: https://habr.com/ru/post/1795617/


All Articles