5

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 2

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi Pawello. That worked with a twist as text will have to be the names array with the name index. Thank you
-3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.