我正在尝试创建价格旁边的商品列表。除ondelete()函数外,其他所有功能似乎都工作正常,我似乎无法找到一种方法来删除价格列表和项目列表中的两个字符串,并且总是给我致命错误,超出范围。试图创建一个数字数组并将其放入foreach循环中,但它仍然给出致命错误,超出范围...
@State var itemn = 0
@State var priceList : [String] = [""]
@State var itemList : [String] = [""]
@State var isEditing = false
func deleteItems(at offsets: IndexSet) {
let a = offsets.count
priceList.remove(at: a)
itemList.remove(at: a)
}
var body: some View {
GeometryReader{ res in
ZStack{
Spacer()
}.padding().background(LinearGradient(gradient: Gradient(colors: [Color(red: 0.171, green: 0.734, blue: 0.955), .white]), startPoint: .bottom, endPoint: .trailing)).background(Color(red: 0.171, green: 0.734, blue: 0.955)).edgesIgnoringSafeArea(.bottom)
ZStack{
VStack{
Form{
Section{
HStack{
Section(header: Text("To-Do List ").font(.largeTitle).fontWeight(.thin)){
Spacer()
Button(action: {
self.itemn += 1
self.itemList.append("")
self.priceList.append("")
print(self.itemList)
}, label: {
Text("Add")
})
}
}
List{
ForEach(0 ... self.itemn, id: \.self){s in
VStack{
HStack{
Text("Title: ")
TextField("Expense ", text: self.$itemList[s])
}
HStack{
Text("Price: $")
TextField("0.00", text: self.$priceList[s]).keyboardType(.decimalPad)
}
Button(action: {
self.priceList.remove(at: 0)
self.itemList.remove(at: 0)
}, label: {
Text("delete")
})
}
}.onDelete(perform: self.deleteItems)
}
}
}.onAppear {
UITableViewCell.appearance().backgroundColor = .clear
UITableView.appearance().backgroundColor = .clear
UITableView.appearance().separatorColor = .clear
}.padding()
Spacer()
}
}
}.navigationBarItems(leading: Text("To - List").font(.largeTitle).fontWeight(.thin).padding(.top))
}
}
更改状态强制同步更新,因此您会错配两个数组。解决方案可能是使用模型项值的数组而不是两个数组,例如
struct Item {
let id = UUID() // id is per-your choice
var item: String = ""
var price: String = ""
}
@State var itemList : [Item] = []
当然还有下面的视图逻辑的更新