I am trying to create a list of items with price next to it. It seems like everything is working perfectly except the ondelete() function, I cant seem to find a way to delete both strings in the pricelist and in the itemlist and always gives me an fatal error, out of range. Tried to create a number array and put it in the foreach loop but it still gave the fatal error, out of range...
@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))
}
}
Changing state force update synchronously so you get misfit two arrays. The solution could be to use array of model Item values instead of two arrays, like
struct Item {
let id = UUID() // id is per-your choice
var item: String = ""
var price: String = ""
}
@State var itemList : [Item] = []
of course with updated below view logic
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.