Home > Blockchain >  Add rows from button press (nested array)
Add rows from button press (nested array)

Time:12-19

I am trying to add rows to a view as the user presses the add button. There are two buttons. One which adds a card and one which adds an expense inside the card. Im confident I have the code working to add cards but when I try to add an Expense inside a card it adds expenses to every card that is shown. How can I make it so that when the user presses the add expense button only the expense rows are added to the one card.

I have two structs one for Card and one for Expense, that I am using to store data.

struct Card: Identifiable {
    var id = UUID()
    var title: String
    var expenses: [Expense]
    
}

struct Expense: Identifiable {
    
    var id = UUID()
    var expenseType: String
    var amount: Double = 0.0
}

ContentView()

struct ContentView: View {
    
    @State private var cards = [Card]()
    @State private var expense = [Expense]()

    var title = ""
    var expenseType = ""
    var amount: Double = 0.0

    var body: some View {
        NavigationStack {
            Form {
                List {
                    
                    Button("Add card") {
                        addCard()
                    }
                    ForEach($cards) { a in
                        Section {
                            TextField("Title", text: a.title)
                            
                            Button("Add expense") {
                                addExpenses()
                            }
                            ForEach($expense) { b in
                                TextField("my expense", text: b.expensetype)
                                TextField("amount", value: b.amount, format: .number)
                            }
                        }
                    }
                }
            }
        }
    }
    func addCard() {
        cards.append(Card(title: title, expenses: expense))
    }
    func addExpenses() {
        expense.append(Expense(expenseType: "", amount: 0.0))
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Any help would be really appreciated.....

CodePudding user response:

It doesn't seem like you need the following line, because each card has an expense array, you should remove it.

@State private var expense = [Expense]()

Then move the addExpenses func inside struct Card

struct Card: Identifiable {
    var id = UUID()
    var title: String
    var expenses: [Expense]
    
    mutating func addExpenses() {
        expenses.append(Expense(expenseType: "", amount: 0.0))
    }
}

Then call

a.wrappedValue.addExpenses()

In the Button

Button("Add expense") {
    a.wrappedValue.addExpenses()
}
  • Related