TextField: How to catch editing changes

With TextFields I can provide a closure in the onEditingChange parameter which fires when editing starts and editing ends (a Bool indicating start/end). I can also provide a closure in the onCommit parameter which fires when enter is pressed.

So, for instance when editing starts, I can change the foreground colour and change it back when I switch to another TextField (editing ends) or press enter (Commit).

However, if I start editing and then hit a Button control, neither closure fires. This is surely a bud??

What can I do?

hi Don, I’ve seen posts on other forums indicating TextField can be a bit fragile. I would try disabling the button until the user taps enter.

I’ve done much better than that! I’ve developed a nice generics-based CustomField struct which handles Strings, Ints, Doubles, Arrays and a range of multi-field custom types such as ProbabilityDistributions and Partitions all supporting validation on both individual fields and multi-fields based on this simple initialiser:

CustomField(editor: EnvironmentObject< Editor >, value: Binding< T >, validator: <((T) → Bool)?)

(If you want to try it out I can send it).

Now I cannot see the merit of the SwiftUI TextField with formatter.

1 Like

Do you have a sample you can send a link for?
James Lee
purduejim [at] mac.com

here below (I hope) is a version that handles a range of single data type such as string. int, double. It’s easy to add protocol conformance for other such types.
I’ve removed the code for collection types because its a not quite to my satisfaction yet. I’ll add it when I’m happy with it.
Comments will be welcome.

PreferencesEditor.zip (61.4 KB)

1 Like