sk65plus
sk65plus

Reputation: 179

swiftUI onDelete. trying to find an item within the structure in the row being deleted

I am confused as to how to retrieve the item 'cal' in the row which is deleted on 'onDelete'. using that to generate a total entry. trying to get 'diary.items[offsets].cal'. hopefully I am explaining this.

the code below generates a list of four entries when '+' sign is hit and provides a total field on the top line. my purpose is to decrement the top line accordingly when a row is deleted

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( )
     }
 }

Upvotes: 2

Views: 974

Answers (1)

try this:

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)
}

Upvotes: 3

Related Questions