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

问题描述

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

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("\($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")
    }
    }
}

解决方法

您需要使用ForEach的另一种变体-一种可以接受 dynamic 内容的变体。

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

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")
    }
}

通过这种方式,您无需使用1 ..< numberOfPeople + 2这样的骇客。