当用户按下“添加”按钮时,我正尝试向视图中添加行。有两个按钮。一个用于添加卡,另一个用于在卡中添加费用。我确信我的代码可以添加卡,但当我尝试在卡中添加费用时,它会将费用添加到显示的每张卡中。我怎样才能使它,当用户按下添加费用按钮时,只有费用行被添加到一张卡。
我有两个结构体,一个用于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()
}
}
任何帮助都将非常感谢.....
1条答案
按热度按时间sycxhyv71#
看起来你不需要下面这行,因为每张卡都有一个费用数组,你应该把它去掉。
然后将
addExpenses
func
移到struct Card
内部那就打电话
在
Button
中