24 Comments

Adding an iOS Container View in Xcode

If you are new to iOS programming, you may not know of a very useful feature in iOS called container views. A container view allows you to create a reusable component that all of your view controllers can share. The containers are easily edited with the storyboard editor of Xcode.  Plus the reusable component is also backed by the power of a separate child view controller.

Before container views were introduced, we had to create reusable views using UIViews stored in xibs. You could not see them in the storyboard next to our view controllers. Then we had to programmatically add them to our view controller when the view loaded. It was a real pain. Now you can add a reusable container view without writing any code.

The example app I built has just two view controllers, and I will create a container view that is shared between them.

ContainerViewComplete2

The first thing to do is find the container view in the object library of Xcode and drag it onto my first view controller. I find it easiest to filter the object library for the thing I am looking for.

PickContainerView

 

AddContainerView2

After dragging the container view, constrain it to have the size and position you want in your view controller. You will see that the child view controller changes size automatically when you constrain the container view in the view controller. I added a blue background and a label called “My Component” to the child view controller of the container so you can easily see it. You will also see a special segue, called an embed segue, is added that links the container view to the child view controller of your component.

Now let’s reuse our component in another view. To do this add another container view in the second view controller. The second container view should have the same size and position of the first one, so that your users will not get confused by the component moving around when you transition. However it is not required that you do so.  In fact for demonstration purposes, I will add my second container view to another area of my second view controller.

AddingSecondContainerView

We will not need the child view controller that was automatically added when you added the container view. Select it and delete it so that you are only left with an empty container view that is not linked to a child view controller. The next step is to link the container view to our child view controller that we already created before. Hold the Ctrl key and drag with the mouse from the container view to the child view controller. Now add an embed segue.

AddEmbedSeque2

That should do it. You now have a child view controller that is shared among two view controllers. You can add this child view controller to as many view controllers as you want. Here is what the finished app looks like.

FirstContainerView


Catch up on my other posts in this series:


For more on using Xcode, read my series on unwind segues: