【发布时间】:2020-12-09 17:06:14
【问题描述】:
我是 Swift 新手,正在为一个项目构建一个营养跟踪应用程序。我需要将用户的食物保存到他们将它们添加到他们的食物日记部分的那一天,该部分显示添加到每餐中的食物。
比如用户添加了一个苹果,这个会保存到今天,一天过去了,显示的数据就会保存到那个日期。
我目前使用 CoreData 保存了带有日期的食品,这显示在列表中:
func saveBreakfast() {
let newBreakfastItem = BreakfastItem(context: self.moc)
newBreakfastItem.id = UUID()
newBreakfastItem.name = self.item.name
newBreakfastItem.calories = Int32(self.totalCalories)
newBreakfastItem.carbs = Int32(self.totalCarbs)
newBreakfastItem.protein = Int32(self.totalProtein)
newBreakfastItem.fat = Int32(self.totalFats)
newBreakfastItem.date = self.dateAdded
do {
if self.mocB.hasChanges { // saves only if changes are made
try? self.mocB.save()
}
}
}
ForEach(self.BreakfastItems, id: \.id) { newBreakfastItems in
HStack{
Text(newBreakfastItems.name ?? "Unknown")
.font(.headline)
.font(.headline)
HStack {
Text("Cal: \(Int32(newBreakfastItems.calories))")
.fontWeight(.light)
.foregroundColor(Color("Green Font"))
Text("F: \(Int32(newBreakfastItems.fat))")
.fontWeight(.ultraLight)
Text("P: \(Int32(newBreakfastItems.protein))")
.fontWeight(.ultraLight)
Text("C: \(Int32(newBreakfastItems.carbs))")
.fontWeight(.ultraLight)
但是,我不确定如何查看保存到过去几天的食物,因为目前该应用程序只是一直添加到同一个列表中,无论它保存在哪一天。
某种形式的 ForEach Date 语句是否可以根据从日历中选择的日期循环浏览视图?
提前致谢!
【问题讨论】:
标签: swift date core-data swiftui