Hi I am really new coding in swift so sorry if I'm asking something stupid. But I can't see the error or the solution an I don't know what to do :( I have this class and structure :
@Published var items : [Items] = []
@Published var showButtons = false
func addItem(id: Int, category: String, image: String) {
items.append(Piercing(id: id, category: [category], image: image))
}
func deleteItem(item: Item) {
if let index = items.firstIndex(of: item) {
item.remove(at: index)
}
}
init() { }
}
struct Item: Identifiable, Decodable, Equatable {
var id: Int
var category: [String]
var image: String
}
then I create a view for this:
struct ItemView: View {
var item: Item
@State private var position = CGPoint(x: 100, y: 100)
@ObservedObject var items: ItemModel = .init()
@State var showButtons = false
var body: some View {
if items.showButtons {
Button (role: .destructive) {
withAnimation {items.deleteItem(item: item)}
} label:{
Image(systemName: "trash")
.font(.body)
.bold()
}
}
VStack {
Image(item.image)
.resizable()
.aspectRatio(contentMode: .fit)
.position(position)
.onTapGesture(count: 1, perform: {
withAnimation { items.showButtons.toggle()}
})
}
}
}
in my ContentView I have this
@StateObject var items: ItemModel = .init()
Right, from another View I add Items to ContentView perfectly, and from the ContentView I can deleteItems too... but I want to add a button in this view can't delete item from the button I have in this view calling deleteItem function from here... Any idea of what I'm doing in a wrong way...
really thanks!