How to add a subview that has its own UIViewController in Objective-C?
Asked Answered
F

2

59

I am struggling with subviews that have their own UIViewControllers. I have a UIViewController with a view (light pink) and two buttons on a toolbar. I want blue view to display when the first button is pressed and the yellow view to display with the second button is pressed. Should be easy if I just wanted to display a view. But the blue view will contain a table, so it needs it's own controller. That was my first lesson. I started off with this SO question where I learned I needed a controller for the table.

So, I am going to back up and take some baby steps here. Below is a picture of a simple starting point with my Utility ViewController (the main view controller) and the other two controllers (blue and yellow). Imagine that when the Utility ViewController (the main view) is first displayed the blue (default) view will be displayed where the pink view is located. Users will be able to click the two buttons to go back and forth and the pink view will NEVER be displayed. I just want the blue view to go where the pink view is and the yellow view to go where the pink view is. I hope this makes sense.

Simple Storyboard image

I'm trying to use addChildViewController. From what I have seen, there are two ways to do this: The Container View in the storyboard or addChildViewController programmatically. I want to do it programmatically. I don't want to use a NavigationController or a Tab bar. I just want to add the controllers and shove the correct view into the pink view when the associated button is pressed.

Below is the code I have so far. All I want to do is display the blue view where the pink view is. From what I have seen I should be able to just addChildViewController and addSubView. This code is not doing that for me. My confusion is getting the better of me. Can somebody help me get the blue view displayed where the pink view is?

This code is not intended to do anything other than display the blue view in viewDidLoad.

IDUtilityViewController.h

#import <UIKit/UIKit.h>

@interface IDUtilityViewController : UIViewController
@property (strong, nonatomic) IBOutlet UIView *utilityView;
@end

IDUtilityViewController.m

#import "IDUtilityViewController.h"
#import "IDAboutViewController.h"

@interface IDUtilityViewController ()
@property (nonatomic, strong) IDAboutViewController *aboutVC;
@end

@implementation IDUtilityViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.aboutVC = [[IDAboutViewController alloc]initWithNibName:@"AboutVC" bundle:nil];
    [self addChildViewController:self.aboutVC];
    [self.aboutVC didMoveToParentViewController:self];
    [self.utilityView addSubview:self.aboutVC.aboutView];
}

@end

--------------------------EDIT------------------------------

The self.aboutVC.aboutView is nil. But I wired it up in the storyboard. Do I still need to instantiate it?

enter image description here

Faithless answered 30/4, 2014 at 22:21 Comment(5)
What's the actual problem you're having?Globeflower
When the view loads, I see the pink view. I'm guessing I must not be coding it correctly.Faithless
Right, OK. First of all, step through the code one line at a time and make sure none of the objects are nil. Specificalyl self.aboutVC, self.utilityView and self.aboutVC.aboutView.Globeflower
You are correct. The self.aboutVC.aboutView is nil. But I wired everything up in the storyboard. I'll update my question with the image.Faithless
What's ur first button and what's your second button? And when u say the blueview where the pink is...do u mean once the blueview is on screen—still the 'X' and the '?' Are hanging there at the top of the view?Tennessee
F
147

This post dates from the early days of modern iOS. It is updated with current information and the current Swift syntax.

In iOS today "everything is a container view". It is the basic way you make apps today.

An app may be so simple that it has just the one screen. But even in that case, each "thing" on the screen is a container view.

It's this easy...

version notes

2020. These days you usually just load a container view from a separate storyboard, which is dead easy. It's explained at the bottom of this post. If you are new to container views, maybe familiarize with the 'classic style' ('same storyboard') container tutorial first.

2021. Updated syntax. Used SO's new '###' pretty headlines. More detail on loading from code.


(A) Drag a container view in to your scene...

Drag a container view into your scene view. (Just as you would drag in any element such as a UIButton.)

The container view is the brown thing in this image. It is actually inside your scene view.

enter image description here

When you drag a container view into your scene view, Xcode automatically gives you two things:

  1. You get the container view inside your scene view, and,

  2. you get a brand-new UIViewController which is just sitting around somewhere on the white of your storyboard.

The two are connected with the "Masonic Symbol Thing" - explained below!


(B) Click on that new view controller. (So that's the new thing Xcode made for you somewhere on the white area, not the thing inside your scene.) ... and, change the class!

It's really that simple.

You're done.


Here's the same thing explained visually.

Notice the container view at (A).

Notice the controller at (B).

shows a container view and the associated view controller

Click on B. (That's B - not A!)

Go to the inspector at the top right. Notice it says "UIViewController"

enter image description here

Change it to your own custom class, which is a UIViewController.

enter image description here

So, I have a Swift class Snap which is a UIViewController.

enter image description here

So where it says "UIViewController" in the Inspector I typed in "Snap".

(As usual, Xcode will auto-complete "Snap" as you start typing "Snap...".)

That's all there is to it - you're done.


How to change the container view - say, to a table view.

So when you click to add a container view, Apple automatically gives you a linked view controller, sitting on the storyboard.

Currently (2019) it happens to make it a UIViewController by default.

That's silly: it should ask which type you need. For example, often you need a table view.

Here's how to change it to something different:

At the time of writing, Xcode gives you a UIViewController by default. Let's say you want a UICollectionViewController instead:

(i) Drag a container view in to your scene. Look at the UIViewController on the storyboard which Xcode gives you by default.

(ii) Drag a new UICollectionViewController to anywhere on the main white area of the storyboard.

(iii) Click the container view inside your scene. Click the connections inspector. Notice there is one "Triggered Segue". Mouse over the "Triggered Segue" and notice that Xcode highlights all of the unwanted UIViewController.

(iv) Click the "x" to actually delete that Triggered Segue.

(v) DRAG from that Triggered Segue (viewDidLoad is the only choice). Drag across the storyboard to your new UICollectionViewController. Let go and a pop-up appears. You must select embed.

(vi) Simply delete all of the unwanted UIViewController. You're done.

Short version:

  • delete the unwanted UIViewController.

  • Put a new UICollectionViewController anywhere on the storyboard.

  • Control-drag from the container view's Connections - Trigger Segue - viewDidLoad, to, your new controller.

  • Be sure to select "embed" on the popup.

It's that easy.


Entering the text identifier...

You will have one of these "square in a square" Masonic symbol things: it is on the "bendy line" connecting your container view with the view controller.

The "masonic symbol" thing is the segue.

enter image description here

Select the segue by clicking on the "masonic symbol" thing.

Look to your right.

You MUST type in a text identifier for the segue.

You decide on the name. It can be any text string. A good choice is often "segueClassName".

If you follow that pattern, all your segues will be called segueClockView, seguePersonSelector, segueSnap, segueCards and so on.

Next, where do you use that text identifier?


How to connect 'to' the child controller...

Then, do the following, in code, in the ViewController of the whole scene.

Let's say you have three container views in the scene. Each container view holds a different controller, say "Snap", "Clock" and "Other".

Latest syntax

var snap:Snap?
var clock:Clock?
var other:Other?

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if (segue.identifier == "segueSnap")
            { snap = (segue.destination as! Snap) }
    if (segue.identifier == "segueClock")
            { clock = (segue.destination as! Clock) }
    if (segue.identifier == "segueOther")
            { other = (segue.destination as! Other) }
}

It's that simple. You connect a variable to refer to the controllers, using the prepareForSegue call.


How to connect in the 'other direction', up to the parent...

Say you're "in" the controller which you have put in a container view ("Snap" in the example).

It can be a confusing to get to the "boss" view controller above you ("Dash" in the example). Fortunately, it is this simple:

// Dash is the overall scene.
// Here we are in Snap. Snap is one of the container views inside Dash.

class Snap {

var myBoss:Dash?    
override func viewDidAppear(_ animated: Bool) { // MUST be viewDidAppear
    super.viewDidAppear(animated)
    myBoss = parent as? Dash
}

Critical: Only works from viewDidAppear or later. Will not work in viewDidLoad.

You're done.


Important: that only works for container views.

Tip, don't forget, that only works for container views.

These days with storyboard identifiers, it's commonplace to just pop new views on the screen (rather as in Android development). So, let's say the user wants to edit something...

    // let's just pop a view on the screen.
    // this has nothing to do with container views
    //
    let e = ...instantiateViewController(withIdentifier: "Edit") as! Edit
    e.modalPresentationStyle = .overCurrentContext
    self.present(e, animated: false, completion: nil)

When using a container view, IT IS GUARANTEED that Dash will be the parent view controller of Snap.

However that is NOT NECESSARILY THE CASE when you use instantiateViewController.

Very confusingly, in iOS the parent view controller is not related to the class which instantiated it. (It might be the same, but usually it is not the same.) The self.parent pattern is only for container views.

(For a similar result in the instantiateViewController pattern, you have to use a protocol and a delegate, remembering that the delegate will be a weak link.)

Note though that these days it's pretty easy to dynamically load a container view from another storyboard - see last section below. It's often the best way.


prepareForSegue poorly named...

It's worth noting that "prepareForSegue" is a really bad name!

"prepareForSegue" is used for two purposes: loading container views, and, segueing between scenes.

But in practice, you very rarely segue between scenes! Whereas almost every app has many, many, container views as a matter of course.

It would make more sense if "prepareForSegue" was called something like "loadingContainerView".


More than one...

A common situation is: You have a small area on the screen, where you want to show one of a number of different view controllers. For example, one of four widgets.

The simplest way to do this: just have four different container views all sitting inside the same identical area. In your code, simply hide all four and turn on the one you want visible.

Easy.


Container views "from code" ...

... dynamically load a Storyboard in to a container view.

2019+ Syntax

Say you have a storyboard file "Map.storyboard", storyboard ID is "MapID", and the storyboard is a view controller for your Map class.

let map = UIStoryboard(name: "Map", bundle: nil)
           .instantiateViewController(withIdentifier: "MapID")
           as! Map

Have an ordinary UIView in your main scene:

@IBOutlet var dynamicContainerView: UIView!

Apple explain here the four things you have to do to add a dynamic container view

addChild(map)
map.view.frame = dynamicContainerView.bounds
dynamicContainerView.addSubview(map.view)
map.didMove(toParent: self)

(In that order.)

And to remove that container view:

map.willMove(toParent: nil)
map.view.removeFromSuperview()
map.removeFromParent()

(Also in that order.) That's it.

Note however in that example, the dynamicContainerView is simply a fixed view. It does not change or resize. This would only work if your app never rotates or anything else. Usually, you would have to add the four usual constraints to simply keep the map.view inside dynamicContainerView, as it resizes. In fact, here is the "world's handiest extension" which one needs in any iOS app,

extension UIView {
    
    // it's basically impossible to make an iOS app without this!
    
    func bindEdgesToSuperview() {
        
        guard let s = superview else {
            preconditionFailure("`superview` nil in bindEdgesToSuperview")
        }
        
        translatesAutoresizingMaskIntoConstraints = false
        leadingAnchor.constraint(equalTo: s.leadingAnchor).isActive = true
        trailingAnchor.constraint(equalTo: s.trailingAnchor).isActive = true
        topAnchor.constraint(equalTo: s.topAnchor).isActive = true
        bottomAnchor.constraint(equalTo: s.bottomAnchor).isActive = true
    }
}

Thus, in any real app the code above would be:

addChild(map)
dynamicContainerView.addSubview(map.view)
map.view.bindEdgesToSuperview()
map.didMove(toParent: self)

(Some folks even make an extension .addSubviewAndBindEdgesToSuperview() to avoid a line of code there!)

A reminder that the order must be

  • add the child
  • add the actual view
  • call the didMove

Removing one of those?

You've added map dynamically to the holder, now you want to remove it. The correct and only order is:

map.willMove(toParent: nil)
map.view.removeFromSuperview()
map.removeFromParent()

Often you will have a holder view, and you want to swap different controllers in and out. So:

var current: UIViewController? = nil
private func _install(_ newOne: UIViewController) {
    if let c = current {
        c.willMove(toParent: nil)
        c.view.removeFromSuperview()
        c.removeFromParent()
    }
    current = newOne
    addChild(current!)
    holder.addSubview(current!.view)
    current!.view.bindEdgesToSuperview()
    current!.didMove(toParent: self)
}
Falcongentle answered 1/5, 2014 at 7:49 Comment(9)
I'll try this when I get into the office. Thank you. I still think you're AWESOME!!! :-)Faithless
You're funny, Joe. This solves my damned problem using a Container View. :-) I wanted to do it in code simply because I did it before in code (once....and over a year ago). I started off, like everybody else, using the storyboard. My ex-coworkers were Sr. iOS developers and didn't want to use storyboards because we had too many windows. So my experience with storyboards and segues are extremely weak. Recently, I've been working with AVFoundation and camera controls and NOT UI stuff. When you get slung around it's easy to forget the basics.Faithless
I might still need a little more help with the little "square in a square" Masonic symbol thingy!!! :-)Faithless
Regarding the damned Masonic Symbol -- what is the issue? ..... I was being funny back. Damned damn it!! :-)Faithless
hey @Joe Let me take a look at it. I actually got this working and was going to share with you how I did it but lately I'm trying to integrate a 3rd party tool and the app is crashing on postNotification. Give me a bit. Yeah, good to hear from you.Faithless
Hey, Joe, I have a new favorite. It made me think of you! :-) Here: https://mcmap.net/q/24316/-why-does-html-think-chucknorris-is-a-color/1735836Faithless
IMHO this is the cleanest way if you want to use IB. Much better than trying to implement via nibs.Phippen
iOS 9's Storyboard References make container views even more awesome. You can define your reusable view(controller) wherever you like and reference it from any container view in multiple, modular storyboards.Hectoliter
@Falcongentle Great tutorial! It would help if you explain a bit how to modify the elements inside a view controller referenced by a container view. It wasn't that obvious for a noob like myself that I could finally change the text of my UILabel inside viewDidLoad because prepare(for segue:) finally made available a valid (not nil) reference to the view controller and its elements (hopefully I used to correct terms. Sorry!)Coraleecoralie
W
5

I see two problems. First, since you're making the controllers in the storyboard, you should be instantiating them with instantiateViewControllerWithIdentifier:, not initWithNibName:bundle:. Second, when you add the view as a subview, you should give it a frame. So,

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.aboutVC = [self.storyboard instantiateViewControllerWithIdentifier:@"aboutVC"]; // make sure you give the controller this same identifier in the storyboard
    [self addChildViewController:self.aboutVC];
    [self.aboutVC didMoveToParentViewController:self];
    self.aboutVC.view.frame = self.utilityView.bounds;
    [self.utilityView addSubview:self.aboutVC.aboutView];
}
Woolley answered 1/5, 2014 at 4:9 Comment(4)
Is setting frame necessary? or it will give the view a default frame according to the storyboard?Wellesley
@Brian, it's probably not necessary if the view you're adding is full screen, but I usually add it any way to make sure. Also, in this case, I wasn't sure if self.utilityView was the full view or the part of the view below the tool bar, in which case, you probably do need to to set the frame.Woolley
@Woolley - Thank you for your information. I wondered if I should be using instantiateViewControllerWithIdentifier but was a bit confused. Also, yes, self.utilityView is not the full view. All 3 subviews are the same size, so I didn't think I needed to set the frame size. I'll try your suggestion when I get into the office.Faithless
@JoeBlow, The OP mentioned using a container view in the storyboard, but said they wanted to do it in code.Woolley

© 2022 - 2024 — McMap. All rights reserved.