How do I add a custom view controller to a ContainerViewController?

Q: How do I add a custom view controller to a ContainerViewController?

A: ContainerViewController supports adding your custom UIViewController subclass as one of its contained child view controller. You can use the initializer ContainerViewController(controllers:titles:) to add the controller or add them using the addViewController(_:) API.

You can optionally show a custom image for your custom child view controller in the segment control (ContainerViewController.filterSegment) that is displayed at the top allowing users to switch between the child controllers. To do so, your custom view controller class should conform to the SegmentImageProviding protocol and implement its segmentImage property returning your desired image.

You can also just display text in the segment control instead of an image by simply setting the title (UIViewController.title) on the controller you are trying to add without conforming to the SegmentImageProviding protocol.

Please ensure that you have at least the title property on your UIViewController set otherwise the controller will not show up in the segment control above. Additionally, the custom view controllers added should not change navigationItem’s bar button items.

Copy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Custom UIViewController subclass confirming to the SegmentImageProviding protocol.
class SegmentImageProvidingContainedController: UIViewController, SegmentImageProviding {
    var segmentImage: UIImage? {
        return UIImage(named: "myCustomImage")
    }
}

...
...
// Adding custom view controllers to a ContainerViewController.

// Will display the image returned by `segmentImage` in the segment control.
let segmentImageProvidingController = SegmentImageProvidingContainedController()
segmentImageProvidingController.view.backgroundColor = UIColor.systemRed

// Will display text instead of an image in the segment control.
let titleProvidingController = UIViewController()
titleProvidingController.title = "TitleProvidingController"
titleProvidingController.view.backgroundColor = UIColor.systemGreen

let containerController = ContainerViewController(controllers: [segmentImageProvidingController, titleProvidingController], titles: nil)