Showing NSView subclass over other view

459 Views Asked by At

I'm trying to show a custom NSView over another view in a OS X App. This is the custom View. It's just a red box:

@interface HelpBarView : NSView

@end

@implementation HelpBarView

- (id)initWithFrame:(NSRect)frameRect
{
    self = [super initWithFrame:frameRect];
    if (self)
    {
        NSLog(@"init");
    }
    return self;
}

- (void)drawRect:(NSRect)dirtyRect {
    [super drawRect:dirtyRect];
    NSLog(@"draw");
    [[NSColor redColor] set];
    NSRectFill(self.bounds);
}

@end

To show this view over another view:

HelpBarView* hbv = [[HelpBarView alloc] initWithFrame:NSMakeRect(10, 20, 100, 100)];
[self.view addSubview:hbv];

This won't show the view. But i can see from the log, that both methods are being called. Also in the XCode Debug View Hierarchy i can see, that the box is in front of the other view and in the correct position. But in the real programm it's not visible.

Also if i do this:

[self.view setSubviews:[NSArray arrayWithObject:hbv]];

Then it will be shown but all other subviews are missing, so this is not what i want.

What am i missing? How can i show a view above another view?

1

There are 1 best solutions below

0
On

Apparently, you need to add this line to your NSView subclass's -initWithFrame method:

self.wantsLayer = YES;

This solved all my problems of the subview not showing up on screen, even though it showed up in Xcode's debug hierarchy view.