momo
momo

Reputation: 3474

How to add custom NSView to Window

I know how to do this in iOS but cannot figure it how to it in Cocoa.

I want to capture keyboard events and I think I need to override the acceptsFirstResponder method to accomplish that (keyDown method being triggered). So I created a class extending NSCustomView and tried to add it in the main Window but I just cannot understand how to do it. So far I added a Custom View to the main View then tried to add it programmatically like:

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

but this is not working. So how can I do this?

Upvotes: 4

Views: 3600

Answers (1)

trojanfoe
trojanfoe

Reputation: 122391

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

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

You should be subclassing 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];

Upvotes: 4

Related Questions