我在使用coredata来存储FoodItems的应用程序中使用swiftUI。在我的应用程序中,我有一个存储在用户设备上的所有foodItems的列表。假定它们应该能够通过长按并按住吃或扔掉的方式删除任何foodItem,但是每次我尝试删除任何foodItem时,它总是删除列表中的第一个,而不是一个我长按了。谁能帮我?这是我的代码段:
ForEach(self.storageIndex.foodItemArray, id:\.self) { item in
RefrigeratorItemCell(icon: item.wrappedSymbol, title: item.wrappedName, lastsUntil: self.addDays(days: Int(item.wrappedStaysFreshFor), dateCreated: item.wrappedInStorageSince))
.gesture(LongPressGesture()
.onEnded({ i in
self.showEatActionSheet.toggle()
})
)
//TODO: Make a diffrence between eat all and throw away
.actionSheet(isPresented: self.$showEatActionSheet, content: {
ActionSheet(title: Text("More Options"), message: Text("Chose what to do with this food item"), buttons: [
.default(Text("Eat All"), action: {
self.managedObjectContext.delete(item)
try? self.managedObjectContext.save()
})
,.default(Text("Throw Away"), action: {
self.managedObjectContext.delete(item)
try? self.managedObjectContext.save()
})
,.default(Text("Cancel"))
])
})
}
答案 0 :(得分:1)
您应该改为使用.actionSheet(item:
并将其移出ForEach
周期,如下面的示例所示
@State private var foodItem: FoodItem? // << tapped item (use your type)
// .. other code
VStack { // << some your parent container
ForEach(self.storageIndex.foodItemArray, id:\.self) { item in
RefrigeratorItemCell(icon: item.wrappedSymbol, title: item.wrappedName, lastsUntil: self.addDays(days: Int(item.wrappedStaysFreshFor), dateCreated: item.wrappedInStorageSince))
.gesture(LongPressGesture()
.onEnded({ i in
self.foodItem = item // << tapped item
})
)
//TODO: Make a diffrence between eat all and throw away
}
} // actionSheet attach to parent
.actionSheet(item: self.$foodItem, content: { item in // << activated on item
ActionSheet(title: Text("More Options"), message: Text("Chose what to do with this food item"), buttons: [
.default(Text("Eat All"), action: {
self.managedObjectContext.delete(item)
try? self.managedObjectContext.save()
})
,.default(Text("Throw Away"), action: {
self.managedObjectContext.delete(item)
try? self.managedObjectContext.save()
})
,.default(Text("Cancel"))
])
})