Respond to Changes in the View Model

So far, our view model is a set of strings that don’t change. The view controller just looks up these strings as it needs them. But that only scratches the surface. MVVM becomes more powerful when the UI responds to changes in the view model.

When a view model property changes, we need a way for the view controller to use the new value. We can do this in various ways, from Apple’s Key-Value Observing to third-party frameworks like Reactive Swift. For our example, we’ll use a simple way built into the Swift language: the didSet observer.

We’ll use this observation technique to move one view concept at a time, starting with whether the Cancel button is enabled.

Is the Cancel Button Enabled?

Add the following ...

Get iOS Unit Testing by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.