This is a simple struct
involving TextField
which works fine.
struct NewProjectView: View {
@State var name = ""
@State var lastName = ""
var body: some View {
VStack{
TextField("Name: ", text: $name)
TextField("Last Name: ", text: $lastName)
}
}
}
Now, I have modified the struct
to accept two parameters, and trying to make them equal to the @State
variables.
struct NewProjectView: View {
var oldName: String
var oldLastName: String
@State var name = oldName // ERROR
@State var lastName = oldLastName // ERROR
var body: some View {
VStack{
TextField("Name: ", text: $name)
TextField("Last Name: ", text: $lastName)
}
}
}
struct NewProjectView_Previews: PreviewProvider {
static var previews: some View {
NewProjectView(oldName: "James", oldLastName: "Morton")
}
}
However, error appears as follow
Cannot use instance member 'oldName' within property initializer; property initializers run before 'self' is available
The I put self.
in front of oldName
and oldLastName
, another appears,
Use of unresolved identifier 'self'
At this point I have no idea what to do. I expect name and last name to be shown in both TextField
s.
If this view is intended to change name and last name then you need @Binding
, not a @State
Like in
struct NewProjectView: View {
@Binding var name: String
@Binding var lastName: String
var body: some View {
VStack{
TextField("Name: ", text: $name)
TextField("Last Name: ", text: $lastName)
}
}
}
so creating it you can pass into old name and last name, say from some model.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.