Home > OS >  Different State Variables for New Textfields in SwiftUI
Different State Variables for New Textfields in SwiftUI

Time:04-25

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.

The scenario is like this: scenario

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?

CodePudding user response:

You want to handle multiple people but you have only one name and one email property.

You need an array. A swifty way is a custom struct

struct Person  {
    var name, email : String
}

In the view replace name and email with an empty array of Person

@State private var people = [Person]()

In the ForEach loop iterate over the indices and bind the text parameter to the person at given index.

I don't have your custom text fields, the code uses the default fields

ForEach(people.indices, id: \.self) { index in
    VStack {
        TextField("Enter name", text: $people[index].name)
        TextField("Enter email", text: $people[index].email)
    }
    .padding()
}

Finally in the button action add a new Person to people

Button {
    print("add person tapped")
    people.append(Person(name: "", email: ""))
  • Related