Question

I hear a lot of people saying that they use Storyboards for laying things out, but for creating reusable views and for other reasons, Storyboards fall short of their expectations and they elect to still use nibs/xibs.

Having entered the iOS development area after Storyboards were accepted practice and Apple started not talking about nibs anymore, I'm confused how to mix the two and there seems to be a dearth of resources or tutorials explaining the combination.

If I want to have a reusable UIView, say with a UIImageView and a UIProgressView embed with in it, do I create one nib file, and use the [NSBundle mainBundle] import to bring it in? Or do I use it like a Storyboard and have one big nib file with reusable views in it, then import the views distinctly?

An explanation of how to use them in tandem, or even just a link to a tutorial would be greatly appreciated. I really want to take advantage of the benefits of nibs alongside Storyboards, but I'm having difficulty understanding it.

Was it helpful?

Solution

There are two ways to pull a view out of a xib.

  • If it is the main view of a view controller, then this just happens more or less automatically when an instance of the view controller needs its view (because they are associated by name or by the way the view controller was instantiated).

  • Otherwise, do this: have the view be the sole top-level object in its xib, and load the xib and grab that sole top-level object, like this:

    NSArray* objects = [[UINib nibWithNibName:@"SomeName" bundle:nil]
                        instantiateWithOwner:nil options:nil];
    UIView* v = objects[0];
    

    And now you can plunk that newly instantiated view into your interface. As you rightly say, you can do that over and over to get more instances.

NOTE: A third way is to load the xib with an owner that has an outlet to the view, but to explain that requires more detail than I want to go into here, and it probably doesn't get you anything you need at the moment.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top