When I create a new OSX project in XCode 4.6, and choose the Cocoa Application template, what I subsequently see in the Interface Builder is an NSWindow, an NSMenu (pre-filled with some menu items), and an NSView inside the NSWindow. However, when I try to delete the NSView and replace it with say an NSTableView, or embed the NSView inside an NSScrollView, I'm unable to do so.
Is the automatically generated NSView special in some way? Does an NSWindow require an NSView to sit on top of it, and not allow some other subclass like NSTableView or NSCollectionView to be the root view in the hierarchy? I know I can change the class in the Identity Inspector, but that doesn't seem to do anything. Any ideas or hints for this newbie?
This is the window's content view. All windows must have one to contain their content, so one is provided by the window by default. While it is possible to use any view you want for the content view (using the setContentView:
method in code), Interface Builder does not currently allow you to replace it, possibly because it can have some unexpected results.
Unless you have a good reason to replace the content view, it is better to just put your view inside of it. You can make your view take the full area and use the autoresizing mask or auto layout constraints to keep it that way. This will make your view appear to be the content view, with the only difference being the extra level of view hierarchy.
If you really want to change the content view, you can do it in Interface Builder by setting a custom class. However, as you have seen, this does not make the view act like the one you chose. Interface Builder ignores the custom class for the purposes of displaying the view and choosing its settings, with the proper class being used at runtime. This is undesirable for most situations, as you do not get to specify any settings.
A better way to change the content view is to do it in code. You can create a view in Interface Builder which is not in any window, and build your hierarchy in it. Then, after the nib is loaded but before the window is shown, your code will replace the window's default content view with your own. For example, if an object has properties called window
and newContentView
, it could change the content view and display the window like this:
[self.window setContentView:self.newContentView];
[self.window makeKeyAndOrderFront:nil];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With