问题描述
当用户滑动删除列表中的条目时,是不是有一个指针可以用来获取被删除条目的信息?在删除条目之前,我想知道类别总数。我遇到了函数 removeItems
的问题,它给出了错误:无法将“IndexSet”类型的值转换为预期的参数类型“Int”
struct CatItem: Codable,Identifiable {
var id = UUID()
var catNum: Int
var catName: String
var catTotal: Double
var catPix: String
var catShow: Bool
}
class Categories: ObservableObject {
@Published var catItem: [CatItem] {
didSet {
}
}
}
struct manCatView: View {
@EnvironmentObject var userData: UserData
@EnvironmentObject var categories: Categories
var pic: String = ""
var body: some View {
List {
ForEach(0 ..< categories.catItem.count) { index in
if index.catShow == true {
HStack {
let pic = categories.catItem[index].catPix
Image(systemName: pic)
.resizable()
.foregroundColor(Color(colors[index]))
.frame(width: 40,height: 40)
Text(categories.catItem[index].catName)
}
}
}
.onDelete(perform: removeItems)
}
.navigationBarTitle(Text("Manage Categories"),displayMode: .inline)
NavigationLink(destination: addCatView()) {Text("Add Categories")
.fontWeight(.bold)}
.font(.title2)
.disabled(categories.catItem.count > 16)
.padding([.leading,.trailing],10)
.accentColor(Color(red: 60/255,green: 160/255,blue: 240/255))
Text("")
Text("")
Text("Add Up to 5 Categories")
Text("Swipe Left to Delete a Category")
Rectangle()
.frame(width: 50,height: 175)
.foregroundColor(.white)
}
func removeItems(at offsets: IndexSet) {
var catTotal: Double = 0.0
//subtract entry amount from category total
catTotal = categories.catItem[offsets].catTotal // <-- need help with index here
userData.totalArray[grandTotal] -= catTotal
userData.totalArray[userTotal] -= catTotal
categories.catItem.remove(atOffsets: offsets)
}
}
解决方法
这里的IndexSet 是一个简单的Indexies 集合,在简单的情况下它只包含一个元素(用户滑动一个一个地删除条目)。因此,为简单起见,您可以为此使用 .first 元素。但更好 - 遍历完整集,它会让你有更多的控制。
因此您需要的代码可能类似于:
func removeItems(at offsets: IndexSet) {
var catTotal: Double = 0.0
offsets.forEach { singleOffset in
//subtract entry amount from category total
catTotal = categories.catItem[singleOffset].catTotal
userData.totalArray[grandTotal] -= catTotal
userData.totalArray[userTotal] -= catTotal
}
categories.catItem.remove(atOffsets: offsets)
}