列表不异步更新列表中的行数?

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

我创建了一个@State 变量numberOfPeople,当用户从选择器中选择人数时,它会更新变量,但底部的列表不会更新行数。我做错了什么!?

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

完整代码:

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("\([=11=]) People")
                    }
                }
            }
            
            
            // TIP SELECTION
            Section (header : Text("HOW MUCH WILL YOU TIP")) {
                
                Picker("Select tip size" , selection: $tipPercentage){
                    ForEach (0 ..< tipPercentages.count) {
                        Text("\(self.tipPercentages[[=11=]]) %")
                    }
                    
                }.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")
    }
    }
}

您需要使用 ForEach 的另一种变体 - 接受 动态 内容的变体。

id: \.self 添加到代码中的每个 ForEach

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

这样你就不需要使用像 1 ..< numberOfPeople + 2.

这样的技巧了