Quick Reference – Load a UIView created in a NIB

I have a few situations where I would like to visually lay out some UIView and writing code just to move something over by a pixel, no back two, no actually the original was fine, etc. is just a pain. I like WYSIWYG. So from time to time I’d like to load a UIView from a NIB because sometimes you need more than one instance of that UIView in your view hierarchy.

It’s dead easy. For a subclass of UIView called MyCustomView, you just need to do the following in Interface Builder:

* Create a NIB file for your view, and lay it all out. Create Outlets as necessary.
* Set the File’s owner in IB to your UIView subclass’ name
* Set the class type of your NIB’s view (much like a view controller’s view property) to your subclass name.
* Any outlets should be relative to the view, NOT the file’s owner

Then in code:

– Implement a method something like:

- (id)initWithNib
{
    // where MyCustomView is the name of your nib
    UINib *nib = [UINib nibWithNibName:@"MyCustomView" bundle:[NSBundle mainBundle]];
    self = [[nib instantiateWithOwner:self options:nil] objectAtIndex:0];
    return self;
}
- (id)initWithCoder:(NSCoder*)aDecoder
{
    self = [super initWithCoder: aDecoder];
    if(self){
        // do your initialization tasks here
    }
    return self;
}
- (void)awakeFromNib
{
   // then do any other initialization tasks here. Possibly interesting to you https://horseshoe7.wordpress.com/2013/02/07/xcode-using-ib-to-configure-custom-classes/
}

Bam! It’s that easy.

2 thoughts on “Quick Reference – Load a UIView created in a NIB

    • Yes indeed! I left it out for the sake of brevity as the post was about making a view from a NIB. i.e. you instantiate only from a nib. But good of you to point that out for the sake of being thorough!

Leave a comment