Dynamic TextFields based on user input using SwiftUI

Viewed 1893

I am trying to create a dynamic set of TextFields which are added after the user presses the add button. Each press will add another set of those fields. I am new to this so please bear with me. I am getting a fatal error: index out of range. Here is a simple example of what I am trying to achieve.

struct ContentView: View {

    @State var name: [String] = []
    @State var counter = 0

    var body: some View {
        Form {
            Section {
                ForEach(0..<counter, id: \.self) { index in
                    TextField("Name", text: self.$name[index])
                }


                Button(action:{
                    self.counter += 1
                }) {
                    Text("Add more")
                }
            }
        }
    }
}
2 Answers

You're increasing the counter without adding new items. If you add a new item to your array it will work without errors:

Button(action:{
    self.name.append("")
    self.counter += 1
}) {
    Text("Add more")
}

But preferably don't use the counter variable at all. If you add a new item to the names array it's count will automatically increase. You can use it in the ForEach loop like this:

ForEach(0..<names.count, id: \.self) { index in
    TextField("Name", text: self.$names[index])
}
Button(action:{
    self.names.append("")
}) {
    Text("Add more")
}

Note: For arrays it's better to use plural names: names instead of name. It indicates it's a collection of items.

SWIFTUI: Here's the code to show multiple dynamic Text() element:

@State var textsArray = ["a","b","c","d"]

    HStack{ ForEach(textsArray, id: \.self)  
    { text in   
     Text("\(text)") 
      }   
     }

You can add more texts into "textsArray" or you can change the values in "textsArray" and it'll be automatically changing on UI.

Related