ios - 如何在 WidgetKit、SwiftUI 中更改午夜 View ?

标签 ios swift swiftui widgetkit

我有一个代码:

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,但我不知道如何做到这一点。
关于如何从 WidgetKit 更改午夜 View 的任何想法?

最佳答案

  • 假设你有一个条目(在你的应用程序中你有 entry.state... 但在这个例子中我使用了一个简化版本):
  • struct SimpleEntry: TimelineEntry {
        let date: Date
        let lesson: Lesson
    }
    
  • 设置您的 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 中,您可以通过任何您想要的类(class)(取决于当天或上一课 - 这取决于您)。您还可以将一个变量传递给一个条目,指示类(class)是否已完成。
    通过设置 .after(nextMidnight)您指示何时重新加载时间轴(以及 WidgetKit View )的策略。

    关于ios - 如何在 WidgetKit、SwiftUI 中更改午夜 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64209612/

    相关文章:

    swiftui - @ViewBuilder 在属性上与 init 中,存储闭包或结果值

    swift - 如何使用 SwiftUI 从 CloudKit 检索数据

    ios - 构建路径时绘制 CGPath

    ios - 使用 NSnumberformatter 从计算得出的数字中删除数字

    swift - GoogleSignIn 不适用于 YouTube API (Swift)

    ios - 在两个文件中的两个类之间传递数据

    没有 UIViewRepresentable 的 SwiftUI map 覆盖

    ios - 如何在 Collection View 中获取索引 path.item - 1 处的单元格

    ios - AFNetworking 序列化正斜杠,使 JSON 负载无效

    ios - Xcode Storyboard : How to fit different screen sizes with 10+ textfields