如何解决列表不异步更新列表中的行数?
我创建了一个@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
这样的骇客。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。