Home > Enterprise >  Swift - How to properly display text using .onSubmit?
Swift - How to properly display text using .onSubmit?

Time:03-14

I'm trying to make a very simple app that asks the user for their name and greets them using the input after the user has pressed enter. I've included my code below:

struct ContentView: View {

    @State private var input: String = ""

    var body: some View {
        VStack {
            TextField("Please enter your name: ", text: $input)
                .onSubmit {
                   Text("Hello, \(input)")
                }
        }
    }
}

As you can see, I'm using the .onSubmit method for TextField() to detect when the user has pressed enter in order to display a string with Text(). My code works fine if I replace Text() with print(), but I'm not trying to display text in the console. At this point, I'm pretty sure I've misunderstood how Text() is supposed to be used and would like a nudge into the right direction.

Thanks in advance.

CodePudding user response:

You cannot put a View into the onSubmit closure.

But you could add a boolean flag and set it to true in the closure

For example

struct ContentView: View {
        
    @State private var input: String = ""
    @State private var showGreeting = false
    
    var body: some View {
    
        VStack {
            TextField("Please enter your name: ", text: $input)
                .onSubmit {
                    showGreeting = true
                }
            if showGreeting {
                Text("Hello, \(input)")
            }
        }
    }
}
  • Related