[英]Q: Bug on Form and TextField [SwiftUI]
When I use TextField
in Form
, the correct value is not displayed until tap the field.当我在
Form
使用TextField
时,在点击该字段之前不会显示正确的值。
The name field is initially displayed dummy
and change to shuji
when tapped.名称字段最初显示为
dummy
并在点击时更改为shuji
。
If I change Form
to VStack
, initial value is displayed.如果我将
Form
更改为VStack
,则会显示初始值。
ContentView.swift内容视图.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 FormTestApp.swift
import SwiftUI
@main
struct FormTestApp: App {
@State var user = User(name: "shuji", email: "shuji@abc.com")
var body: some Scene {
WindowGroup {
ContentView(user: $user)
}
}
}
Tested on iPhone 12 iOS 15.1, and Simulator iOS 15.0在 iPhone 12 iOS 15.1 和模拟器 iOS 15.0 上测试
To "make it work", move the .onAppear {...}
to just after a TextField
, like this:要“使其工作”,请将
.onAppear {...}
移动到TextField
,如下所示:
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)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.