Encode Behaviors into Reusable View Controllers

Using the American spelling

Steven Curtis

--

Photo by Jonathan Hanna

Difficulty: Beginner | Easy | Normal | Challenging
This article has been developed using Xcode 12.1, and Swift 5.3

Prerequisites

Extension: Extensions add new functionality to a class, struct, enum or protocol

Override: The process in which a subclass changes a method, property or type in the parent class Protocol: A blueprint on methods, properties and requirements to suit a piece of functionality

UIViewController: A view controller is an intermediary between the views it manages and the data of your app

Break down!

The principle here is that we are trying to break view controllers up — which essentially is attempting to make iOSs UIViewControllers more closely follow the Single Responsibility Principle.

Now this is an article I’ve written to support a blog post by Soroush along with a similar post by Bryan — however I failed to follow either of these propertly for the appearance and suppression of the UINavigationBar, so this article covers that (so all credit goes to Soroush and Bryan).

The example behaviour

Within this article we are going to hide the UINavigationBar in the first of two UIViewController instances within a UINavigationController. In order to do so this article will use the function:

(we shall see that concrete implementation later).

The solution

We are using Swift, so it makes sense that we would want to use protocols

The protocol It is possible to use any of any of the UIViewController lifecycle events in order to implement these behaviours.

The protocol

This protocol is called ViewControllerLifecycleBehavior:

--

--