如何在WidgetKit,SwiftUI的午夜更改视图? [英] How to change view on midnight in WidgetKit, SwiftUI?

查看:57
本文介绍了如何在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: entryDate, 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的午夜更改视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆