Swiftui 快速删除。正在尝试在要删除的行中的结构中查找项
我不知道如何检索在“onDelete”上删除的行中的项目“cal”。使用它生成一个总条目。正在尝试获取“日记.items[offset].cal”。希望我能解释一下 当点击“+”号时,下面的代码生成一个包含四个条目的列表,并在顶行提供一个总计字段。我的目的是在删除行时相应地减少顶行Swiftui 快速删除。正在尝试在要删除的行中的结构中查找项,swiftui,Swiftui,我不知道如何检索在“onDelete”上删除的行中的项目“cal”。使用它生成一个总条目。正在尝试获取“日记.items[offset].cal”。希望我能解释一下 当点击“+”号时,下面的代码生成一个包含四个条目的列表,并在顶行提供一个总计字段。我的目的是在删除行时相应地减少顶行 import SwiftUI struct Entry: Identifiable { let id = UUID() let food : String /* changing item to fo
import SwiftUI
struct Entry: Identifiable {
let id = UUID()
let food : String /* changing item to food */
let cal : String
}
class Diary: ObservableObject {
@Published var items = [Entry]()
}
struct ContentView: View {
@ObservedObject var diary = Diary()
@State var fooditem = ""
@State var calories = ""
@State var totcals = 0
var body: some View {
Form {
Button(action: {
var entry = Entry(food: fooditem, cal: calories)
let count = 1...4
for number in count {
entry = Entry(food: String(number), cal: String(number*2))
self.diary.items.append(entry)
totcals += number*2
}
}) { Image(systemName: "plus") }
VStack{
Text(" totals = " + String(totcals))
}
List {
ForEach(diary.items, id:\.food) { item in
Text(item.food + ": " + item.cal + " cals")
}.onDelete(perform: removeItems)
}
}
}
func removeItems( at offsets: IndexSet) {
diary.items.remove(atOffsets: offsets)
// need a way find cals associated with this offset in order
// to subtract it from total onDelete
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView( )
}
}
试试这个:
func removeItems(at offsets: IndexSet) {
for i in offsets.makeIterator() {
let theItem = diary.items[i]
// theItem.cal
// do something with theItem.cal
}
diary.items.remove(atOffsets: offsets)
}