0

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.
                })
1

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.