3

我有一个代码:

struct ContentView: View {
    let entry: LessonWidgetEntry
    private static let url: URL = URL(string: "widgetUrl")!
    var body: some View {
        VStack {
            switch entry.state {
            case .none:
                ProgramNotStartedView()
            case .currentLesson(let lesson):
                LessonView(lesson: lesson, imageName: entry.program?.imageName)
            case .lessonCompleted(let lesson):
                LessonCompletedView(lesson: lesson)
            case .programCompleted:
                ProgramCompletedView()
            }
        }.widgetURL(ContentView.url)
    }
}

在午夜,LessonCompletedView 应该更改为 LessonView,但我不知道该怎么做。关于如何从小部件更改午夜视图的任何想法?

4

1 回答 1

6
  1. 假设你有一个条目(在你的应用程序中你有entry.state...,但在这个例子中我使用了一个简化版本):
struct SimpleEntry: TimelineEntry {
    let date: Date
    let lesson: Lesson
}
  1. 设置您的 TimelineProvider 以在下一个午夜后刷新时间线:
struct SimpleProvider: TimelineProvider {
    ...

    func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> Void) {
        let currentDate = Date()
        let midnight = Calendar.current.startOfDay(for: currentDate)
        let nextMidnight = Calendar.current.date(byAdding: .day, value: 1, to: midnight)!

        let entries = [
            SimpleEntry(date: currentDate, lesson: Lesson()) // pass the lesson here
        ]

        let timeline = Timeline(entries: entries, policy: .after(nextMidnight))
        completion(timeline)
    }
}

在 TimelineProvider 中,您可以通过任何您想要的课程(取决于当天或上一课 - 这取决于您)。您还可以将变量传递给条目,指示课程是否已完成。

通过设置.after(nextMidnight)策略,您可以指示您希望何时重新加载您的时间线(以及您的小部件视图)。

于 2020-10-05T15:04:37.663 回答