Search code examples
swiftuiviewcontrollertvos

Multiple UIViewControllers inside master UIViewController in Swift


I am building a game in Swift 3 for tvOS. The game has a CPU intensive game background that includes several animations. This background is a UIViewController dedicated to this task. I would like to use this background in all other UIViewControllers.

When navigating between the ViewControllers the background animation need to continue smoothly. What would be the best way to do this?

Schematic example of the shared background UIViewController:

Example


Solution

  • Use parent child view controller containment.

    Create a parent view controller. Have your constant animation run in that view controller's content view.

    Add a container view to that view controller and an embed segue, linked to the first child view controller you want to go inside the container view.

    Then use the view controller child view controller support methods and transition methods to swap the child view controller for another child view controller. (See transition(from:to:duration:options:animations:completion:). Also see the section "Implementing a Container View Controller" in the UIViewController Class description in the Xcode docs. In particular, this bit:

    Here are the essential methods you might need to call:

    • addChildViewController(_:)

    • removeFromParentViewController()

    • willMove(toParentViewController:)

    • didMove(toParentViewController:)