Custom init for UIViewController in Swift with interface setup in storyboard
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Custom initialization in `UIViewController` is a common requirement when setting up a view controller with specific attributes or dependencies. This can include passing data, configuring the controller with certain behaviors, or ensuring compliance with specific initial states. While Interface Builder provides much of the basic setup for view controllers, custom initializers allow for a more tailored setup process. In this article, we'll explore how to set up custom initializers for a `UIViewController` that also uses Interface Builder for layout.
Understanding Initialization in Swift
In Swift, every object must be fully initialized before being used. This rule applies to setting up properties, configuring dependency injections, and ensuring setup is complete before the object is functional. Unlike other classes that might adopt convenience initializers, `UIViewController` is initialized via `init(coder:)` when working with storyboards. This is a constraint that sometimes leads to common pitfalls when setting up custom initializers.
Custom Initializers
When you create a `UIViewController` with a storyboard, it's inherently initialized with `init(coder:)`. Any custom initialization you'd like to perform typically has to acknowledge and potentially incorporate this fact. You typically need to create an additional initializer that accepts the parameters you need, while making sure that the storyboard-instantiated object is appropriately set up.
Example Implementation
Let's consider creating a simple custom initializer in a `UIViewController` that is setup with Interface Builder:
- Required Initializer (`init(coder:)`):
- This initializer is required and must be implemented in subclasses using storyboards. It's the entry point for the storyboard embedding instantiation process.
- In the example, `labelText` is set to a default string to ensure it's initialized.
- Custom Initializer:
- The custom initializer includes an additional parameter `labelText`. This parameter allows us to configure the `UIViewController` with this property.
- The `super.init(coder:)` call is essential to ensure the base class handles initialization.
- Storyboard Constraints:
- Remember that if a `UIViewController` is designed in a storyboard, initialization must conform to the configuration provided by Interface Builder.
- This often means managing or refactoring logic to suit IB constraints.
- Maintaining Separation of Concerns:
- The view controller's initializer should remain focused on setting initial states, with minimal UI concerns.
- Dependency Injection:
- Custom initializers can be beneficial when using a dependency injection pattern, allowing for greater decoupling and testability.

