[英]Erase more than one string with ondelete on swiftUI
我正在尝试创建一个带有价格的项目列表。 除了 ondelete() function 之外,似乎一切都运行良好,我似乎无法找到删除价格表和项目列表中的两个字符串的方法,并且总是给我一个超出范围的致命错误。 试图创建一个数字数组并将其放入 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))
}
}
更改 state 强制同步更新,因此您会得到两个不合适的 arrays。 解决方案可能是使用 model 项目值数组而不是两个 arrays,例如
struct Item {
let id = UUID() // id is per-your choice
var item: String = ""
var price: String = ""
}
@State var itemList : [Item] = []
当然更新了下面的视图逻辑
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.