NSView subclass for NSMenuItem
I want to create a subview of NSView and link 开发者_StackOverflowit to a MenuView.xib.
I'll have:
- MenuView.m
- MenuView.h
- MenuView.xib
in xcode I created my xib and set as customclass my 'MenuView'. Now I would like to add my new view programmatically via a command like this:
NSView *vv = [[MenuView alloc] initWithFrame:CGRectMake(0, 0, 300, 200)];
NSMenuItem *newItem = [[NSMenuItem alloc] initWithTitle:@"title" action:nil keyEquivalent:@""];
[newItem setView:vv];
but I just see an empty space without any content. How can I tell the class MenuView.m to render with the MenuView.xib file? Is that wrong?
Thanks.
Use an NSViewController
, it's designed for loading views from a nib file. In your nib file, set NSViewController
as the class of File's Owner and then set the view
outlet of File's Owner so that it points to your view in the nib.
Then you can just do this:
NSViewController* viewController = [[NSViewController alloc] initWithNibName:@"YourNibName" bundle:nil];
YourCustomView* view = [viewController view]; //this loads the nib
[viewController release];
//do something with view
To load a view from a nib (adapted from another answer of mine):
NSNib *nib = [[NSNib alloc] initWithNibNamed:@"MenuView" bundle:nil];
NSArray *nibObjects;
if (![nib instantiateNibWithOwner:self topLevelObjects:&nibObjects]) return nil;
NSMenuItem *item = nil;
for (id obj in nibObjects)
if ([obj isKindOfClass:[NSMenuItem class]]) {
item = obj;
break;
}
[someView insertSubview:item];
If you want something other than self
as the file owner, change the parameter to instantiateNibWithOwner:
.
精彩评论