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:

Image for post
Image for post

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

Image for post
Image for post

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

Image for post
Image for post

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 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.

Image for post
Image for post

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

Image for post
Image for post

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

Image for post
Image for post

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

Image for post
Image for post

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

iOS Developer, speaker and educator. Top Udemy and LinkedIn instructor. Lead instructor at DigitalCrafts. https://www.udemy.com/user/mohammad-azam-2/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store