Home > Net >  How to create a function for the button to print the data typed in texfields in the console
How to create a function for the button to print the data typed in texfields in the console

Time:03-19

struct ContentView: View {

@State private var name : String = ""

var body: some View {
    NavigationView{
        Form{
       
            Button(action: {
                print(Textfield)
            }) {
                Text("Salvar")
            }

i need print the result typed at Textfield

CodePudding user response:

You are confusing the view, TextField, which allows you to input text with the variable which stores the result of the input. You can't print the view into which you type, but you can print the value of the variable. Therefore:

struct ContentView: View {
    // name holds the value
    @State private var name : String = ""
    
    var body: some View {
        NavigationView{
            Form{
                // TextField lets you change the value
                TextField("Name", text: $name)
                Button(action: {
                    // prints the value to the console
                    print(name)
                }) {
                    Text("Salvar")
                }
            }
        }
    }
}
  • Related