mistersister
mistersister

Reputation: 19

SwiftUI Textfield format onEditingChanged

I have a formatted SiwftUI TextField and I want it to format when editing changes. What would be the correct way of doing that?

TextField("", value: $binding, formatter: $formatter,
                    onEditingChanged: { (editingChanged) in
                        //How to force formatting here?
                    },
                    onCommit: {
                        //Here formatting happens.
                })

Upvotes: 0

Views: 2553

Answers (1)

Cenk Bilgen
Cenk Bilgen

Reputation: 1445

OnEditing closure is called when the editing mode of the TextField changes. So it would be called with true when you start editing and called with false when you end (and so would onCommit at the end unless you cancel, but need to check).

I don't think that's what you want. If you want to format while the user is changing the text in the TextField, try something like this:

  TextField("text", text: $text).padding()
            .onReceive(text.publisher) { (c) in
                print("Got \(c)")
                self.text = self.text.uppercased()
        }

But, keep in mind when you apply the formatting to $text, the new formatted version will be published, triggering a second closure call. This double call may or may not be an issue depending on the formatting you want and how text is used elsewhere.

Upvotes: 2

Related Questions