Hi all I'm new to SwiftUI and am trying to find a neat way to add or remove TextFields when either the plus or minus of a steeper is pressed.
I currently have
@State private var answers: [String] = ["", ""]
Stepper(onIncrement: {
if(numberOfAnswers < 10){
answers.append("")
numberOfAnswers += 1
}
},
onDecrement: {
if(numberOfAnswers > 2){
answers.removeLast()
numberOfAnswers -= 1
}
}) {
ForEach(answers.indices, id: \.self) { index in
TextField("Answer", text: $answers[index])
}
However this results in an Index out of bounds exception when onDecrement is called.
I have tried wrapping the String to conform to Identifiable (with the @State
inside the struct declaration), using ForEach(answers)
however this produces a warning stating that the variable will not be updated.
I have tried solutions posted here but to no avail.
I do not need to persistently store the result of this, as it will be passed to a separate function making an API call on button press.
Any help for this would be much appreciated.