本文介绍了如何在 WidgetKit、SwiftUI 中更改午夜视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代码:

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,但我不知道该怎么做.关于如何从小部件更改午夜视图的任何想法?

At midnight LessonCompletedView should change to LessonView, but I am not sure how to do that.Any ideas on how to change views on midnight from the widget?

推荐答案

  1. 假设您有一个 Entry(在您的应用中您有 entry.state... 但在本例中我使用了一个简化版本):
  1. Assuming you have an Entry (in your app you have entry.state... but for this example I used a simplified version):
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 中,您可以传递任何您想要的课程(取决于当天或上一课 - 由您决定).您还可以将一个变量传递给一个 Entry 来指示课程是否已完成.

In the TimelineProvider you may pass any lesson you want (depending on the day or the previous lesson - it's up to you). You may also pass a variable to an Entry indicating whether the lesson is completed.

通过设置 .after(nextMidnight) 策略,您可以指示何时重新加载时间轴(以及窗口小部件视图).

By setting the .after(nextMidnight) policy you indicate when do you want your Timeline (and therefore you Widget View) to be reloaded.

这篇关于如何在 WidgetKit、SwiftUI 中更改午夜视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 08:26