我想知道你是否可以帮我回答一个SwiftUI的问题。具体来说,我试图在午夜或日期更改时更新视图中的ForEach循环。我的模型中的所有日期都是“dd.MM.yyyy”格式,并按日期获取ForEach循环。如何在更改日期或午夜时实时地用新事件重新加载ForEach循环?任何提示或建议将不胜感激!
虚拟机
import Foundation
@MainActor
final class TodaysEventsViewModel: ObservableObject {
@Published var events = [EventModel]()
@Published var event = [Event]()
@Published var selectedEvent: Event?
@Published var date = Date()
private var stringDate: String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd.MM.yyyy"
let currentDateString = dateFormatter.string(from: date)
return currentDateString
}
init() {
fetchEvents()
getTodaysEvents()
}
private func fetchEvents() {
let eventsData = Bundle.main.decode([EventModel].self, from: "EventsData.json")
events = eventsData
}
private func getTodaysEvents() {
if let index = events.first(where: {$0.date == stringDate}) {
event = index.event
}
}
}
查看
import SwiftUI
struct TodaysEventsView: View {
@StateObject private var viewModel = TodaysEventsViewModel()
var body: some View {
VStack(spacing: 7.5) {
ForEach(viewModel.event, id: \.id) { event in
Button {
self.viewModel.selectedEvent = event
} label: {
EventCell(event: event)
}
}
}
.sheet(item: $viewModel.selectedevent) { event in
EventDetailView(event: event)
}
}
}
1条答案
按热度按时间bihw5rsg1#
您可以观察日历中的日期更改,如: