Performing Actions On Value Changes In SwiftUI

Performing Actions On Value Changes In SwiftUI
⏱ Reading Time: 4 mins

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 let’s set the limit of the allowed characters to 150. The bare minimum implementation for that requires a label to prompt users, and a text editor. The typed text is hold in a property marked with the @State property wrapper:

View with a label and an empty textview.

Even though the above presents the text editor where users can type in, there is an actual problem that is not solved by the above implementation. How can we make it possible to prevent users from typing more than 150 characters in the text editor?

In addition to that, our view is not so user-friendly right now. To change that, let’s make the decision to add two more views so users are aware of how far they’ve gone with writing; a progress view and a text view indicating the number of typed characters.

Both of the above have the same requirement; it’s necessary to know the length of the typed text. Before we get to see how to solve that, let’s update the initial code so it displays a progress and a text view as well:

progress is another state property which holds the writing progress value as a double number. It’s given as argument to the progress view.

To the actual point of the post now, what we really need is to be notified whenever the value of the review property gets changed. In order to achieve that, it’s necessary to use the onChange(_:) view modifier, which we’ll apply to the text editor like so:

There are two things to do in the above closure:

  1. To assign the length of the review to the progress property as a double value.
  2. To check if the length of the review is more than 150 characters or not. In the former case, we’ll just drop the last characters that exceed the limit.

Converting the two points above into code is shown right next:

This addition to the code is good enough to make our view work properly, and be user-friendly at the same time:

Animated GIF with text being written in the text editor, a progress bar indicating the typing process and a text view displaying number of typed characters out of 150.

Old and new values

Although it’s not necessary in the above example, it’s often needed to know both the old and the new value of the property we are observing for changes. The closure of the onChange(_:) provides them both like so:

The previous value of the review property is captured by the closure -the [review] value-, while the new one is given as argument -the newValue-.

Notice that:

  • the old value in the capture list must have the name of the property, while you can name the new value whatever you want, and,
  • accessing the actual property from within the closure is now possible with the self keyword (self.review).

As said, knowing both the previous and the new value of a property that gets changed can be vital in various cases. Therefore, keep the above in mind if you ever need to access them both.

Conclusion

The onChange(_:) view modifier is a quite important one, as it’s the way to go in order to observe for changes in property values. Use it as the event that will trigger further actions in your app, and update the user interface if necessary. The example presented above was thorough enough in order to showcase how this modifier works. Thank you for reading, stay safe and take care.

If you found this post useful then please consider sharing it! Also, subscribe to my newsletter in order to be notified about everything new published here directly in your inbox, and follow me on Twitter, on YouTube, on Medium and other social media.

👉 Wanna say thanks or support me?

Buy Me a Coffee!

Stay Up To Date

Subscribe to my newsletter and get notifiied instantly when I post something new on SerialCoder.dev.

    We respect your privacy. Unsubscribe at any time.