ios 通过按下按钮添加行(嵌套数组)

k5hmc34c  于 2022-12-20  发布在  iOS
关注(0)|答案(1)|浏览(91)

当用户按下“添加”按钮时,我正尝试向视图中添加行。有两个按钮。一个用于添加卡,另一个用于在卡中添加费用。我确信我的代码可以添加卡,但当我尝试在卡中添加费用时,它会将费用添加到显示的每张卡中。我怎样才能使它,当用户按下添加费用按钮时,只有费用行被添加到一张卡。
我有两个结构体,一个用于Card,一个用于Expense,我用它们来存储数据。

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
}

内容视图()

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

任何帮助都将非常感谢.....

sycxhyv7

sycxhyv71#

看起来你不需要下面这行,因为每张卡都有一个费用数组,你应该把它去掉。

@State private var expense = [Expense]()

然后将addExpensesfunc移到struct Card内部

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

那就打电话

a.wrappedValue.addExpenses()

Button

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

相关问题