How to add a custom NSView to a window

I know how to do this in iOS, but can't figure out how to do it in Cocoa.

I want to capture keyboard events, and I think I need to override the acceptsFirstResponder method to accomplish this (called keyDown method). So I created a class that extends NSCustomView and tried to add it to the main window, but I just can’t figure out how to do this. So far I have added a custom view to the main view, and then tried to add it programmatically, for example:

TestView *view = [[TestView alloc] init]; [[_window contentView] addSubview:view]; 

but it does not work. So how can I do this?

+4
source share
1 answer

To see if a view has been added to the window, you can override the view viewDidMoveToWindow method and register the [self window] value to check (if it is nil , then the view has been removed from the window)

 - (void)viewDidMoveToWindow { NSLog(@"window=%p", [self window]); [super viewDidMoveToWindow]; } 

You should be subclassed by NSView , not NSCustomView , and initWithFrame is the designated initializer for NSView , not init .

Try:

 TestView *view = [[TestView alloc] initWithFrame:NSMakeRect(0, 0, 100, 200)]; [[_window contentView] addSubview:view]; 
+4
source

All Articles