Home > Software engineering >  Swift - Multiple textfields updating instead of one
Swift - Multiple textfields updating instead of one

Time:12-05

I am trying to save the inputs of multiple TextFields in an array, but when I try to enter a text in either of the text fields in the first iteration of the VStack, the text in the next iteration also updates, and vice versa.

Here is what I tried:

@State var numberOfFlashcards: Int = 2
@State var question: String = ""
@State var answer: String = ""
ForEach(1...numberOfFlashcards, id:\.self){ index in
    Text("Flashcard \(index)")
    VStack{
        // question text field
        TextField(text: $question) {
            Text("Enter question")
        }
                                
        // answer text field
        TextField(text: $answer) {
            Text("Enter answer")
        }
    }
}

CodePudding user response:

You need each pair of quaestion and answer to be bound to a separate instance of the variable. So a simple way to do this -

  1. Create a structure, like:
struct QA: Hashable, Identifiable {
    let id = UUID()
    var question: String = ""
    var answer: String = ""
}
  1. Then in your view create an array of that structure as your state:
@State var qas = [QA](repeating: QA(), count: 2)
  1. And bind each instance in array to each instance of the text field in ForEach in your view (as $qas[index].<...>):
VStack {
   ForEach(qas.indices, id: \.self){ index in
       Text("Flashcard \(qas[index].question)")
       // question text field
       TextField(text: $qas[index].question) {
           Text("Enter question")
       }
       
       // answer text field
       TextField(text: $qas[index].answer) {
           Text("Enter answer")
       }
   }
}

(I moved VStack to the top of the hierarchy, as otherwise all items ar overlapping, unless you already have it somewhere higher up, so it may not be actually required)

CodePudding user response:

Because $question and $answer are binding and refer to the same variables that are defined in the outer scope, each value of $question or $answer in a flashcard is going to be the same for all of the flashcards.

  • Related