gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:11:11 26 4
gpt4 key购买 nike

我创建了一个@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变体-一种可以接受动态内容的变体。
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这样的黑客程序。

关于ios - 列表不异步更新列表中的行数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63963065/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com