1

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

1
  • I wonder was this working in iOS 14.x ? Commented Nov 4, 2021 at 8:23

1 Answer 1

4

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)
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I had the same issue in iOS 15 and this actually worked. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.