我正在运行一个函数,以填充费用清单。我需要运行功能以使用.onAppear(perform: fetchRows)
填充列表,以便列表在视图显示后立即更新。
Xcode不喜欢我正在运行一个用于填充consumptionList的事实。我该如何工作?有没有更好的方法解决这个问题?
@State var expensesList: [ExpensesList]?
var body: some View {
NavigationView{
VStack{
if expensesList != nil{
List{
ForEach(self.expensesList!) { <-- Type '() -> ()' cannot conform to 'View'; only struct/enum/class types can conform to protocols
(log: ExpensesList) in {
Button(action: {
self.editExpense = log
})
ExpenseRow(name: log.expense, date: log.date, amount: log.cost, account: log.account)
}
}.onDelete(perform: onDelete)
}
}
}.navigationTitle("Expense List")
struct ExpensesList: Identifiable, Equatable {
let id: UUID
let expense: String
let cost: Double
let account: String
let date: Date
}
func fetchRows(){
Expenses.fetchAllExpensesInDateRange(context: self.context) { (results) in
guard !results.isEmpty else { return }
self.expensesList = results.map({ (result) -> ExpensesList in
print(result.id,result.expenseName,result.expenseCost, result.expenseAccount, result.expenseDate)
return ExpensesList(id: result.id, expense: result.expenseName, cost: result.expenseCost, account: result.expenseAccount, date: result.expenseDate)
})
}
}
我用来编辑费用的工作表在这里。如您所见,我使用名为Expenses的Core Data实体存储我的费用对象。
.sheet(item: $editExpense, onDismiss: {
self.editExpense = nil
})
{
(log: Expenses) in
ExpenseDetail(
context: self.context,
editExpense: log,
name: log.expenseName ?? "",
amount: String(log.expenseCost),
category: log.expenseCategory ?? "",
date: log.expenseDate ?? Date(),
account: log.expenseAccount ?? "",
isMonthly: log.expenseIsMonthly
).environment(\.managedObjectContext, self.context)
}
答案 0 :(得分:3)
在{
之后有一个额外的(log: ExpensesList) in {
,而您的Button
没有content
参数。
请尝试以下操作(我假设ExpenseRow
应该是按钮的content
)
ForEach(self.expensesList!) { log in
Button(action: {
self.editExpense = log
}) {
ExpenseRow(name: log.expense, date: log.date, amount: log.cost, account: log.account)
}
}
请注意,在SwiftUI 2中,您可以直接在if-let
块中使用控制流语句(如@ViewBuilder
)
if let expensesList = expensesList {
List {
ForEach(expensesList) { log in
// ...
}
}
}