Get Text value from TextField in SwiftUI


Using TextField in SwiftUI, a developer can create an editable text interface. In this tutorial, I am going to focus on how to get the value from a TextField in SwiftUI with the help of a simple example.

To do so, first, create our private variable with @state property. Then we will create our TextField and provide the state variable value to bind with.

Let’s see the code given below:

import SwiftUI

struct ContentView: View {
    
    @State private var fruit: String = "Banana"
   
    var body: some View {
            
            VStack {
                TextField("Enter your favourite fruit", text: $fruit).padding().border(Color.blue)
                
                Text("I Love, \(fruit)!")
            }
        
  }
}

If you run the above program on an iOS simulator device, you should be able to see a message text appear containing the text that you type in the SwiftUI text field. From this result, we confirm that we are able to get the text value from our TextField in SwiftUI.

Every time user types something in the TextField, the value will be stored in the state variable fruit.

We are using a Text() view to see the value of our TextField. We pass the fruit variable to the Text view in the above code as given below:

Text("I Love, \(fruit)!")

That’s happening because we have bonded our text field with the state property value we declared. As the TextField is binding to the state variable, so changing the value in TextField also changes the state value. So we just have to get the state property value to get the text value of the TextField.