ritesh.hh

Child View Controllers, Part 1

March 23, 2019

If we are trying to refactor a massive view controller, probably embedding child view controllers is one of the ways to go about it. With this post, I'm starting a series where I'll experiment with this concept and share my findings with everyone. I'll be making a movie app as a demo project to go with these posts. Every post will tackle only one problem which can be solved via child view controllers.

Part 1: AppStarterViewController

Every app has the first screen and for our app let's call it HomeViewController. Now basically there are two ways we can show it as a first screen i.e via storyboard or programmatically. In this post, we will programmatically set it inside AppDelegate. As we all know we just have to set the root view controller of the app's window i.e.

window.rootViewController = HomeViewController()

which looks perfectly fine but the moment we want to do some setup before we launch the first screen like fetching user info or initialize database then all that logic goes either inside AppDelegate or SomeKindOfManager or even HomeViewController where none of the options feel right. So how can we solve it via child view controller?

To achieve it let's make a new controller say AppStarterViewController which is a subclass of UIViewController and we basically add HomeViewController as a child view controller of AppStarterViewController,

class AppStarterViewController: UIViewController {
    lazy var homeVC: HomeViewController = {
        HomeViewController()
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        add(child: homeVC)
    }
}

// AppDelegate
window.rootViewController = AppStarterViewController()

where add(child:) is just a helper function which makes it easier to add child controllers. That's it! Now we can use AppStarterViewController to take care of any logic which is associated with the app's launch and HomeViewController is only responsible for home screen related logic ๐Ÿ™Œ

Before we end this post let's take a look at the app's view heirarchy i.e. UIWindow -> AppStarterViewController -> HomeViewController,

1

Feedbacks are welcome. If you want to reach out or have any comments then ping me at Twitter. Thanks for reading ๐Ÿ™‡โ€โ™‚๏ธ


Ritesh Gupta

Hi, Iโ€™m Ritesh Gupta, iOS Engineer from India ๐Ÿ‡ฎ๐Ÿ‡ณ. Here, I mainly write about Swift and iOS app development.
twitter โ†’ @_riteshhh.
More about me.