[英]How to perform onDelete with Section item inside ForEach in SwiftUI
[英].onDelete not working in sorted ForEach - SwiftUI
我不知道為什么這不起作用。 我一直都是這樣做的,唯一的區別是sorted
方法。
ForEach(userData.fruits_and_vegetables.sorted { $0.item < $1.item}) { grocery in
DetailCardView(item: grocery.item, itemCount: grocery.count)
}.onDelete { (offset) in
self.userData.fruits_and_vegetables.remove(atOffsets: offset)
}
幫助! 謝謝
你得到一個數組的offset
,但試圖將它應用到另一個數組......真的行不通。
相反,它應該完成,例如
let sorted = userData.fruits_and_vegetables.sorted { $0.item < $1.item}
...
ForEach(sorted) { grocery in
DetailCardView(item: grocery.item, itemCount: grocery.count)
}.onDelete { (offset) in
for i in offset {
if let found = self.userData.fruits_and_vegetables.firstIndex(where: { $0 == sorted[i] }) {
self.userData.fruits_and_vegetables.remove(at: found)
}
}
}
並更好地將onDelete
sorted
和 content 移動到您的userData
類中。
我也有同樣的問題。 在remove
函數中,我添加了相同的排序:
func remove(at offsets: IndexSet) {
for index in offsets {
let grocery = userData.fruits_and_vegetables.sorted { $0.item < $1.item }[index]
grocery.delete // Your delete method
}
}
在我的代碼中,我也有一個.filter
,我也在那里添加了它。 一切正常!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.