One of the constants in a developer’s life is seeing code and knowing you’re doing it wrong, but not really knowing how to fix it and get it right. Due to whatever reason: no time… My Facebook like loading indicator article was no exception, the way I loaded a specific view from a separate nib felt so bad. Yet I posted it since holding it back for another 4 weeks was no option either. A week ago I had a eureka moment and it all made sense at around 2am on a Saterday morning. Here’s the correct method to load a view from a separate nib file.
Instead of looping through the contents of the nib, the key are IBOutlets. Create a NSView IBOutlet in your controller class were you’ll want to use the view. Next step is to open your nib file which contains your external view and change the File Owner’s class identity to the controller class you’ve just extended with the IBOutlet for the view. Now just ctrl-drag from the File Owner to your view and select your desired IBOutlet from the list.
Now you’ve connected your controller and the external view, yet the IBOutlet will not be hooked up automatically when your controller’s created. This is a good thing because we can postpone loading the extra nib to when it’s really necessary saving resources for other, more important stuff. This is a practice Apple encourages, using multiple nib files and loading them dynamically when needed.
This is the code needed to load the nib, it’ll automaticall hook up your controller’s IBOutlet to your view.
[[NSBundle mainBundle] loadNibNamed:@"YourNibName" owner:self options:nil];
Simple? Indeed, yet it took me a while to realize using an external nib is basically just the same as putting all your views in a single nib container. It’s all based on hooking up IBOutlets.
Tags: nib
Very nice piece of code! But how would you do it if the view was on top of multiple cells? With other words, how would you get the view with rounded corners so you don’t see any white around the rounded image?
I think you can set the background color of the “parent” view to the clear color, although that might have to be done in code and not in the Interface Builder. If you make sure the outer corners of your rounded image (which is placed on top of the “parent” view) are transparent, you should have what you wanted.