我正在使用 SwiftUI 创建一个显示过去和当前日期的日历视图。我希望根据特定值以红色或绿色显示过去的日期。但是,我当前的实施仅适用于当天。谁能帮我修改代码,使其也适用于过去的日期?
这是 SimpleCalendar 视图的代码:
struct SimpleCalendar: View {
let startDate: Date
let endDate: Date
let content: (Date) -> Color
let items: FetchedResults<Item>
@State private var selectedMonth: Date
@Environment(\.calendar) var calendar
init(startDate: Date, endDate: Date, content: @escaping (Date) -> Color, items: FetchedResults<Item>) {
self.startDate = startDate
self.endDate = endDate
self.content = content
self.items = items
_selectedMonth = State(initialValue: Calendar.current.date(from: Calendar.current.dateComponents([.year, .month], from: Date()))!)
}
func dailyValue(for date: Date) -> Int {
let startOfDay = Calendar.current.startOfDay(for: date)
let endOfDay = Calendar.current.date(byAdding: .day, value: 1, to: startOfDay)!
let itemsForDay = items.filter { $0.timestamp! >= startOfDay && $0.timestamp! < endOfDay }
let value = itemsForDay.reduce(0) { total, item in
total + (item.isGood ? 1 : -1)
}
return value
}
func colorForDate(_ date: Date) -> Color {
if hasEntry(for: date) {
let value = dailyValue(for: date)
return value >= 0 ? Color.green : Color.red
} else {
return Color.gray
}
}
var body: some View {
VStack {
Picker("Select Month and Year", selection: $selectedMonth) {
ForEach(availableMonthsAndYears(), id: \.1) { monthAndYear, date in
Text(monthAndYear).tag(date)
}
}
.pickerStyle(MenuPickerStyle())
.padding()
HStack {
ForEach(months, id: \.self) { month in
VStack {
CalendarMonthGrid(startDate: startDate, endDate: endDate) { date in
Group{
let value = dailyValue(for: date)
ZStack {
content(date)
.frame(width: 25, height: 25)
.cornerRadius(5)
Text("\(calendar.component(.day, from: date))")
.foregroundColor(value != 0 ? .black : .white)
}
}
}
}
}.padding()
}
}
}
我试过修改 colorForDate 函数,但它似乎对过去的日期不起作用。任何帮助,将不胜感激。谢谢!
这是我的 CoreData 实体的样子: