skip to Main Content

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)

2

Answers


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

    Login or Signup to reply.
  2. 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()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search