Home > Software engineering >  Q: Bug on Form and TextField [SwiftUI]
Q: Bug on Form and TextField [SwiftUI]

Time:10-27

When I use TextField in Form, the correct value is not displayed until tap the field.

The name field is initially displayed dummy and change to shuji when tapped.

If I change Form to VStack, initial value is displayed.

ContentView.swift

import SwiftUI

struct User {
    var name: String
    var email: String
}

struct ContentView: View {
    @Binding var user: User
    @State private var name: String = "dummy"
    @State private var email: String = ""

    var body: some View {
        NavigationView {
            Form {
                TextField("Name", text: $name)
                TextField("Email", text: $email)
            }
            .navigationTitle("Edit user")
            .toolbar {
                Button("Save") {
                    user.name = name
                    user.email = email
                }
            }
        }
        .onAppear {
            name = user.name
            email = user.email
        }
    }
}

FormTestApp.swift

import SwiftUI

@main
struct FormTestApp: App {
    @State var user = User(name: "shuji", email: "[email protected]")
    var body: some Scene {
        WindowGroup {
            ContentView(user: $user)
        }
    }
}

Tested on iPhone 12 iOS 15.1, and Simulator iOS 15.0

CodePudding user response:

To "make it work", move the .onAppear {...} to just after a TextField, like this:

struct ContentView: View {
    @Binding var user: User
    @State private var name: String = "dummy"
    @State private var email: String = ""
    
    var body: some View {
        NavigationView {
            Form {
                TextField("Name", text: $name)
                TextField("Email", text: $email)
                    .onAppear {   // <--- here
                        name = user.name
                        email = user.email
                    }
            }
            .navigationTitle("Edit user")
            .toolbar {
                Button("Save") {
                    user.name = name
                    user.email = email
                }
            }
        }.navigationViewStyle(.stack)
    }
}
  • Related