user11371080
user11371080

Reputation:

Create empty Text Field in View with Button Click SwiftUI

I have an app with a concept of a recipe has multiple ingredients. I want people to be able to post their recipes with how ever ingredients they wish. To do this, I populate a view with one field and a button that will create another empty text field on tap and append it to the view. How can I achieve this? This is some boilerplate I have so far.

struct TestView: View {
    @State private var ingredientName = ""

    var body: some View {
        HStack {
            TextField("Example Field", text: $ingredientName)
            Button(
                action: {
                    // Do something to add another empty text field to the view
                },
                label: {
                    Image(systemName: "plus.circle")
                        .foregroundColor(Color.black)
                }
            )
        }
    }
}

Upvotes: 1

Views: 1895

Answers (1)

aheze
aheze

Reputation: 30228

You want a dynamic number of text fields, right? Whenever you want a dynamic number of views, you want ForEach. This generates a view for each element in an array.

struct TestView: View {
    @State var ingredientNames = [""] /// array of ingredients
    
    var body: some View {
        VStack { /// vertical stack of ingredients
            ForEach(ingredientNames.indices, id: \.self) { index in
                TextField("Example Field", text: $ingredientNames[index]) /// use each element in the array
            }
            
            Button(action: {
                /// Add another empty text field to the view
                ingredientNames.append("")
            }) {
                Image(systemName: "plus.circle")
                    .foregroundColor(Color.black)
            }
        }
    }
}

Result:

Press plus button to add text field

Upvotes: 3

Related Questions