I've got this piece of code below with a textfield, but the issue is when I try to add a swipeAction to enable the users to delete items on every row as needed, it doesnt work. Does anyone know a walkaround to make the swipeAction work. I really appreciate in advance. I am pretty sure it is possible to add a swipeAction to each row but not sure how
import SwiftUI
struct TableItems: View {
@State private var items: [Item] = [Item(id: UUID(), name: "", quantity: "", price: "", complete: "", shopName: "", isComplete: false)]
@State private var item: Item = Item(id: UUID(), name: "", quantity: "", price: "", complete: "", shopName: "", isComplete: false)
@EnvironmentObject var tableModel: TableModel
var body: some View {
VStack {
HStack {
Button(action: {
// Add your camera button action here
}) {
Image(systemName: "camera")
}
.foregroundColor(.cartvoltDarkBlue)
Spacer()
Button {
hideKeyboard()
} label: {
Image(systemName: "keyboard.chevron.compact.down")
}
.foregroundColor(.cartvoltDarkBlue)
Spacer()
Button(action: {
self.addRow()
// Add your to do checklist button action here
}) {
Image(systemName: "plus")
}
.foregroundColor(.cartvoltDarkBlue)
}
.padding()
HStack {
Text("Item")
Spacer()
Text("Quantity")
Spacer()
Text("Price")
Spacer()
Text("Store")
Spacer()
Image(systemName: "globe")
.foregroundColor(.black)
}
.padding(10)
ScrollView {
ForEach(0..<items.count, id: \.self) { index in
HStack {
HStack {
Button(action: {
var mutableItem = self.items[index]
mutableItem.isComplete.toggle()
// Find the index of the `item` object in the `items` array
for (i, element) in self.items.enumerated() where element.id == mutableItem.id {
self.items[i] = mutableItem
}
}) {
Image(systemName: self.items[index].isComplete ? "checkmark.circle" : "circle")
}
TextField("Enter item name", text: self.$items[index].name, onCommit: {
self.addRow()
})
Divider()
}
TextField("Enter item quantity", text: self.$items[index].quantity, onCommit: {
self.addRow()
})
Divider()
TextField("Enter price", text: self.$items[index].price, onCommit: {
self.addRow()
})
Divider()
TextField("Enter store name", text: self.$items[index].shopName, onCommit: {
self.addRow()
})
}
.padding(.leading, 5)
.padding(.bottom, 10)
}
}
}
}
func addRow() {
items.append(Item(id: UUID(), name: "", quantity: "", price: "", complete: "", shopName: "", isComplete: false))
}
}
struct Item: Identifiable {
var id: UUID
var name: String
var quantity: String
var price: String
var complete: String
var shopName: String
var isComplete: Bool
}
.onDeleteand.swipeActionsonly work onList, so I suggest to change the ScollView to List.Also I strongly recommend to use the initializer
ForEach($items) { $item ininstead of indices, it makes your code cleaner and your life easier: