SwiftUI-OnDelete后刷新崩溃

时间:2020-09-13 02:58:37

标签: swiftui

使用下面的代码,我在表单的第二部分有一行。执行onDelete时,我可以看到(通过断点)它已成功从数组中删除了记录。正文由于是状态变量而被刷新,然后以Fatal error: Index out of range: file崩溃。当它再次尝试执行ForEach时会发生崩溃,由于数组为空,这时此时应该不显示任何内容。

struct BuyerCheckout: View {
    @State private var subTotal:Double!
    @State private var tax:Double!
    
    @State private var fees = [FeeModel(type: "", amount: 0.00)]
    
    var body: some View {
        NavigationView {
            Form {
                Section(header: Text("Gross Amounts")) {
                    HStack {
                        Text("Subtotal: $")
                        TextField("Purchase Subtotal", value: $subTotal, formatter: NumberFormatter.currency)
                            .keyboardType(.decimalPad)
                    }
                    HStack {
                        Text("Tax: $")
                        TextField("Purchase Tax", value: $tax, formatter: NumberFormatter.currency)
                            .keyboardType(.decimalPad)
                    }
                }
                
                Section(header: Text("Other Fees")) {
                    ForEach(fees.indices, id: \.self) {
                        FeeCell(fee: self.$fees[$0])
                    }
                    .onDelete(perform: removeRows)
                }
            }.gesture(DragGesture().onChanged { _ in
                UIApplication.shared.windows.forEach { $0.endEditing(false) }
            })
            .padding()
            .navigationBarTitle("Checkout")
            .onAppear {
                UITableViewCell.appearance().selectionStyle = .none
            }
        }
}

我也用这种方式对ForEach进行索引,因为变量表示FeeCell的绑定。我无法通过数组的ForEach迭代器传递绑定。不确定是否相关,但我想提一提。

0 个答案:

没有答案