View Controller Containment to Inject Empty Views

A very common scenario for an iOS application is to fetch information from the server and then display it in a UITableView control. In some cases the server returns no data at all and we have to notify the user that there is no data to be displayed.

A very common approach is to create an EmptyView control which can be assigned to the UIViewController’s view. This replaces the UIViewController’s view with the contents of the EmptyView control as shown below in the implementation:

The EmptyView control can be as simple or as complicated as you like. We created a simple EmptyView for this example as shown below:

If the server returns an empty array the EmptyView is assigned as the main view of the screen.

This approach works and is simple! But this approach is also very limited. Now, if we need to show an empty view on some other screen we will have to write the same code again.

View Controller Containment:

View Controller Containers allows different view controllers to be injected into the parent view controller. Based on the data returned from the server we can inject the EmptyViewController or PokemonsTableViewController.

The ContainerViewController is responsible for adding the particular controller to the screen.

The caller indicates in the build closure which view controller they want to inject.

If the server returns data then it is displayed on the UITableView control as shown below:

On the other hand if server does not return anything then the EmptyViewController takes over.

You can download the complete code which can be pasted in Swift Playgrounds here.

Like what you read? Give Mohammad Azam a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.