List not asynchronously updating the number of rows in my list?

Viewed 52

I've created a @State variable numberOfPeople and when a user selects the number of people from the Picker, it updates the variable but the List at the bottom doesn't update the number of rows. What am I doing wrong!?

List {
    ForEach (1 ..< numberOfPeople + 2) { num in
        Text("\(num) People")
    }
}

FULL CODE:

struct ContentView: View {
    
    @State private var checkAmount = ""
    @State private var  numberOfPeople = 2
    @State private var tipPercentage = 2
    
    let tipPercentages : [Int] = [10,15,20,25,0]
    
    var totalPerPerson : Double {
        //Calcualte the total per person here
        let peopleCount = Double(numberOfPeople + 2)
        let tipSelection = Double(tipPercentages[tipPercentage])
        let orderAmount = Double(checkAmount) ?? 0
            
        let tipValue = orderAmount / 100 * tipSelection
        let grandTotal = orderAmount + tipValue
        let amountPerPerson = grandTotal / peopleCount
        
        return amountPerPerson
    }
   
    
    var body: some View {
        
        NavigationView{
        Form {
            
            //Amount enter
            Section{
                TextField("Amount" , text: $checkAmount )
                    .keyboardType(.decimalPad)
                
                Picker("Number of people" , selection: $numberOfPeople) {
                    ForEach (2 ..< 100){
                        Text("\($0) People")
                    }
                }
            }
            
            
            // TIP SELECTION
            Section (header : Text("HOW MUCH WILL YOU TIP")) {
                
                Picker("Select tip size" , selection: $tipPercentage){
                    ForEach (0 ..< tipPercentages.count) {
                        Text("\(self.tipPercentages[$0]) %")
                    }
                    
                }.pickerStyle(SegmentedPickerStyle())
            }
            
            // TOTAL PAY PER PERSON
            Section {
                Text("£ \(totalPerPerson , specifier: "%.2f / Person")")
            }
            
            //Break down of each person amount
            List {
                ForEach (1 ..< numebrOfPeople + 2){ num in
                    Text("\(num) People")
                }
            }
        }.navigationBarTitle("SPLITTER")
    }
    }
}
1 Answers

You need to use a different variant of ForEach - one that accepts dynamic content.

Add id: \.self to every ForEach in your code:

Picker("Number of people", selection: $numberOfPeople) {
    ForEach(2 ..< 100, id: \.self) {
         Text("\($0) People")
    }
}
List {
    ForEach(1 ... numberOfPeople, id: \.self) { num in
        Text("\(num) People")
    }
}

This way you don't need to use hacks like 1 ..< numberOfPeople + 2.

Related