'How to separate input values for each Textfield?
I stored the user's input into a dictionary, but the variables name and amount seems to not be a separate value for each Textfield rows. I tried adding self. to name and amount, but that seemed to not do anything. How can I implement this?
@Binding var numPeople: Int
@State var dict: [String : Float] = [:]
@State var name: String = ""
@State var amount: Float = 0.00
.
.
.
ForEach(1...numPeople, id:\.self) { stack in
HStack {
TextField("Name", text: $name)
.padding()
Text("Amount in $:")
TextField("", value: $amount, formatter: NumberFormatter())
.keyboardType(.numberPad)
.onReceive(Just(amount)) { _ in
dict[name] = amount
}
.padding()
}
}
Thank you!
Solution 1:[1]
In your code you are using the same variables name and amount for all rows that you iterate with ForEach. If you want to have each row with their own fields managed separately, you need to separate the views.
Here below, a very schematic example of how it works:
In the parent view, the ForEach will call a subview:
@Binding var numPeople: Int
// Make @State vars private
@State private var dict: [String : Float] = [:]
// Note that you don't use the variables name and amount here
.
.
.
ForEach(1...numPeople, id:\.self) { stack in
// Pass the dictionary, it will be updated by the subview
SubView(dict: $dict)
}
Create a subview that will separately manage each name/ amount:
struct SubView: View {
@Binding var dict: [String : Float]
@State private var name: String = ""
@State private var amount: Float = 0.00
var body: some View {
HStack {
TextField("Name", text: $name)
.padding()
Text("Amount in $:")
TextField("", value: $amount, formatter: NumberFormatter())
.keyboardType(.numberPad)
// I don't know why you need this, if the amount is
// updated in this view. Maybe you can just use
// dict[name] = amount, dropping the .onReceive()...
// ... but it depends on your code
.onReceive(Just(amount)) { _ in
dict[name] = amount
}
.padding()
}
}
private func whatToDoWithNameAndAmount() {
// Do whatever else you need with these variables
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | HunterLion |
