在swiftUI上使用ondelete擦除多个字符串



我正在尝试创建一个旁边有价格的项目列表。除了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))
}

}

更改状态强制同步更新,这样您就可以得到两个不匹配的数组。解决方案可以是使用模型Item值的数组,而不是像那样使用两个数组

struct Item {
let id = UUID() // id is per-your choice
var item: String = ""
var price: String = ""
}
@State var itemList : [Item] = []

当然有更新的视图下逻辑

最新更新