SwiftUI: An updated approach to limit the amount of characters in a TextField view

Martin Albrecht
2 min readFeb 5, 2022
Photo by Markus Winkler on Unsplash

Since my last article about how to limit the amount of characters in a SwiftUI TextField, it seems Apple has changed a lot of things with publishers and bindings, so that the old example is not working anymore.

Here’s is an updated version which is working with current and older versions of iOS.

The view modifier

In the previous example I made use of a view model and some proxy binding magic to limit the length of the input value. This approach is not only a bit dirty in retrospective, but also not working anymore in iOS 15.

This time I’ll make use of a simple view modifier to do the job which makes things much easier and better to maintain:

First thing to do is to create a view modifier with two variables: a binding to the value and an integer for the maximum length. Instead of using a proxy binding I utilize the onChange(of:perform:) (for iOS 14 and above) and onReceive(_:perform:) (for older iOS versions) methods this time.

Lines 23–27 are a simple extension to the View structure to make the use of the modifier more convenient.

Complete example

Here’s a complete example with a simple view for postal code input:

Lines 3–19 are the view modifier from before, followed by a simple view with some form to enter a postal code and a label to show the entered value.

In line 28 I utilize the function to attach the view modifier from before to the text field.

In this example the expected postal codes are five digits long, so we set the maximum to 5.

The rest should be pretty straight forward and self explanatory… 😉

--

--