在 iOS 14 个小部件上渲染图像

Render Images on iOS 14 Widgets

我正在开发 iOS 14 小部件扩展。

我有 3 张图片要循环显示并创建时间轴来显示这些图片。

func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
    var entries: [ImageEntry] = []
    let currentDate = Date()
    
    for i in 1 ..< 4 {
        let imageNumber = String(i)
        let currentImage = "image_" + imageNumber
        let entry = ImageEntry(date: currentDate,image: currentImage)
        entries.append(entry)
    }

    let nextUpdateDate = Calendar.current.date(byAdding: .minute, value: 5, to: currentDate)!
    let timeline = Timeline(entries: entries, policy: .after(nextUpdateDate))

    completion(timeline)
}


struct WidgetModuleEntryView : View {
var entry: Provider.Entry

var body: some View {
    Image(entry.image)
        .resizable()
        .scaledToFill()
    }
}

第一张图像总是渲染,但后续图像不是。

可能是什么问题?

构建时间表您需要为每个条目指定明确的条目日期。策略参数用于重新创建下一个时间线。

所以你的getTimeline应该看起来像

func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
    var entries: [ImageEntry] = []
    let currentDate = Date()

    for i in 1 ..< 4 {
        let imageNumber = String(i)
        let currentImage = "image_" + imageNumber
        let entryDate = Calendar.current.date(byAdding: .minute, value: (i-1)*5, to: currentDate)!
        let entry = ImageEntry(date: entryDate, image: currentImage)
        entries.append(entry)
    }

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