the_critic
the_critic

Reputation: 12820

Cocoa - How do I initialize a view programmatically ?

I have a problem understanding how to initialize a view without hooking it up in my nib-file. So what I want to do is, instead of dragging in a view and assigning it a dedicated class, I want to programmatically add it to my window in my app delegate.

I don't really know how wrong this is, but I tried something like this in my AppDelegate:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    DView *dV = [[DView alloc]initWithFrame:NSMakeRect(0, 0, 1000, 600)];
    [self.window addSubview:dV];
}

I figured that the window is an NSView as well, so why not just add it to it ? But this crashes and ends in an infinite loop. I hope you can help me. Thanks.

Upvotes: 2

Views: 1278

Answers (1)

justin
justin

Reputation: 104698

yes,

MONView * view = [[MONView alloc] initWithFrame:someFrame];

is correct.


I figured that the window is an NSView as well

It is not an NSView (it is an NSResponder). As Richard Stahl points out, you should interact with the window's content view instead: [window.contentView addSubview:view];

Upvotes: 3

Related Questions