SwiftUI汽车费用记录应用:实现费用累计总额字段
解决方案
你不需要单独维护一个totalCost状态变量,直接通过计算属性从费用列表中实时求和即可,这样能保证总费用始终和列表同步。以下是具体修改步骤:
1. 修改ContentView,添加计算属性替代状态变量
删除@State private var totalCost = 0.0,添加一个计算属性来实时计算总费用:
struct ContentView: View { @StateObject var expenseList = ExpenseList() @State private var isShowingAddView = false // 新增计算属性,实时计算总费用 private var totalCost: Double { expenseList.itemList.reduce(0) { $0 + $1.amount } } var body: some View { NavigationView { VStack { VStack(alignment: .trailing) { Text("Total Cost") .font(.headline) // 显示计算后的总费用,用货币格式 Text(totalCost, format: .currency(code: "USD")) .font(.title) .bold() } .padding() Form { // 原列表代码保持不变 List { ForEach(expenseList.itemList) { trans in HStack{ Text(trans.item) .font(.headline) Spacer() VStack(alignment: .trailing) { HStack { Text("Amount: ") .font(.caption).bold() Text(trans.amount, format: .currency(code: "USD")) .font(.caption) } } } } .onDelete(perform: removeItems) } } .navigationTitle("Expenditure") .toolbar { Button { isShowingAddView = true } label: { Image(systemName: "plus") } } .sheet(isPresented: $isShowingAddView) { AddView(expenseList: expenseList) } } } } func removeItems(at offsets: IndexSet) { expenseList.itemList.remove(atOffsets: offsets) } }
2. 代码说明
- 计算属性
totalCost使用reduce方法遍历itemList,将所有amount累加,每次列表变化(添加、删除项目)都会自动重新计算。 - 因为
expenseList是@StateObject,itemList是@Published属性,当列表数据更新时,SwiftUI会自动刷新视图,总费用也会实时更新。 - 保留了你的数据持久化逻辑,重启应用后总费用依然会从保存的列表中正确计算。
这样修改后,总费用字段就能持续、准确地累计所有费用,无论添加还是删除项目,都会自动更新。
内容的提问来源于stack exchange,提问作者Greg
相关产品推荐
相关产品推荐

