0

Is it possible to replace every whitespace that is created by pressing the spacebar with another character, which in this case is an underscore, while the user is typing in the text field?

I found something about

.replacingOccurrences(of: "", with: "_")

but don't know how to apply it in real-time while typing is occurring.

Here is the text field I am using with a simple state variable:

TextField("Enter a username", text: $txt)
                    .padding()
                    .disableAutocorrection(true)
                    .autocapitalization(.none)
Milly Alfaro
  • 299
  • 3
  • 15

2 Answers2

3

The simplest version of this is to listen to changes of txt with onChange:

struct ContentView : View {
    @State private var txt = ""
    
    var body: some View {
        TextField("Enter a username", text: $txt)
            .padding()
            .disableAutocorrection(true)
            .autocapitalization(.none)
            .onChange(of: txt) { newValue in
                txt = newValue.replacingOccurrences(of: " ", with: "_")
            }
    }
}

You'll likely want a more robust solution for finding whitespace, so you may want to apply some of the solutions to finding whitespace characters here or here with this onChange method.

jnpdx
  • 45,847
  • 6
  • 64
  • 94
-1

and also you can show your text Field and Text like this

var body: some View {
        let replace = txt.replacingOccurrences(of: " ", with: "_")
        TextField("Enter a username", text: $txt)
                            .padding()
                            .disableAutocorrection(true)
                            .autocapitalization(.none)
                           
                Text("Your username: \(replace)")
        .padding()
Saurabh Pathak
  • 879
  • 7
  • 10
  • Why not just `Text("Your username: \(txt)")`? – jnpdx Jan 25 '22 at 06:39
  • yes , you can do, but sometime user put any value with special characters in Text field then it will be helpful if they wanna show replace string – Saurabh Pathak Jan 25 '22 at 06:48
  • In your example, there doesn't seem to be any difference between `txt` and `replace` -- they both have the same `replacingOccurrences(of:with:)` called on them. – jnpdx Jan 25 '22 at 06:50