Member-only story
Performing Actions On Value Changes In SwiftUI
Building the user interface of an app constitutes a task that requires significant amount of time and effort; it has to be providing the best user experience, and be unique and original at the same time. There is no doubt that SwiftUI framework has come to make that process much easier and fun comparing to UIKit. Although most of the work with it is usually fast and straightforward, there are times that things might not be that obvious.
One of those things is the topic of this post. Quite often we need to trigger additional actions or update the user interface, but only after a change to a property’s value has taken place. Sometimes that’s the result of user actions, some other times it’s the result of internal processes in the app. No matter where changes come from, the fact remains the same; it’s necessary to be able to perform actions when property values change in SwiftUI views.
But since we are talking about SwiftUI, we all know that besides views there also the view modifiers; and in this case, a specific view modifier is all we need since iOS 14 and above; the onChange(_:)
.
Understanding onChange with an example
Let’s suppose that we want to create a view in a SwiftUI-based app in order to allow users to write a short review. For the sake of the example…