Search code examples
objective-cstoryboardxibreusability

Design one XIB and re-use it in different UIViewControllers


I have one UIView that I want to use in every of my UIViewControllers. The main UI is designed with Storyboard. The extra UIView has its own XIB.

So I don't want to put the UI of the extra UIView by hand into every UIViewController, and connect the outlets on every UIViewController. So I thought maybe it is possible to create the UI, and the connections in one XIB and then somehow reuse it. Is this possible? If yes how?


Solution

  • Just add this line to your ViewControllers to have a reference to your custom view:

    YourView *yourView = (YourView *)[[NSBundle mainBundle] loadNibNamed:@"YourXIB"
                                                                   owner:self
                                                                 options:nil].firstObject;
    

    But since you want this custom view in all of your ViewControllers, I recommend having one UIViewController subclass that contains the line above, then subclass that UIViewController for each additional one in your project. That way you'll have a reference to your custom view in each ViewController, but only have to write this line once.