I am new to SwiftUI and there is a scenario in which I can add more than one person's data and every time I tap on the button, it will collect new person's data.
I add data on one textfield, it updates on every textfield because there is only one state variable for the textfield. My problem is how can I add multiple State variables for the textfield as the textfields have no fixed number. My code is:
import SwiftUI
struct TextFieldText: View {
@State private var name = ""
@State private var email = ""
@State var totalValue: Int = 1
var body: some View {
VStack(spacing: 30) {
ForEach((1...totalValue).reversed(), id: \.self) {_ in
VStack {
CustomTextfield(text: $name, placeHolder: "Enter name", title: "Enter Name")
CustomTextfield(text: $email, placeHolder: "Enter email", title: "Enter Email")
}
}
Button {
print("add person tapped")
totalValue = totalValue + 1
} label: {
ZStack {
RoundedRectangle(cornerRadius: 60)
.frame(width: 180, height: 45)
.foregroundColor(Color(ColorName.appBlue.rawValue))
Text("Add another person")
.foregroundColor(.white)
.font(Font.custom(InterFont.bold.rawValue, size: 14))
}
}
Spacer()
}
}
}
struct TextFieldText_Previews: PreviewProvider {
static var previews: some View {
TextFieldText()
}
}
I want to add different data on every textfield. How can I achieve it in SwiftUI?

You want to handle multiple people but you have only one
nameand oneemailproperty.You need an array. A swifty way is a custom struct
In the view replace
nameandemailwith an empty array ofPersonIn the
ForEachloop iterate over the indices and bind thetextparameter to the person at given index.I don't have your custom text fields, the code uses the default fields
Finally in the button action add a new
Persontopeople