How Do I Add a Custom View Controller to a ContainerViewController?

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

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

Ensure you have at least the title property on your UIViewController set; otherwise, the controller won’t show up in the segment control above. Additionally, the custom view controllers added shouldn’t change navigationItem’s bar button items:

// The custom `UIViewController` subclass conforming 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)