0

I am interested in implementing a basic image transition animation with the iOS 14 Widget extension.

My goal is to:

  • animate Image change every 0.10 seconds
  • loop endlessly, over 6 Images

The problem:

  • The Images do not animate nor cycle through in my widget

More details here:

I have a class called AnimatingImage

struct AnimatingImage: View {
    let images: [Image]

    @ObservedObject private var counter = Counter(interval: 0.10)
        
    var body: some View {
        images[counter.value % images.count]
    }
}

private class Counter: ObservableObject {
    private var timer: Timer?

    @Published var value: Int = 0
    
    init(interval: Double) {
        timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { _ in self.value += 1 }
        print ("has timer")
    }
}

It is used inside my Widget's main View

struct SleepCheckerWidgetView : View {
    let entry: LastSleepEntry

    var body: some View {

        let images = [Image("moon_1"),
                      Image("moon_5"),
                      Image("moon_10"),
                      Image("moon_15"),
                      Image("moon_20")
        ]
        
        
        VStack(alignment: .leading, spacing: 4) {
            Text("4:44")
                .font(.system(.title2))
                .foregroundColor(.white)
                .bold()
            AnimatingImage(images: images)
                            .scaledToFit()
            
        }.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .center)
            .padding()
    }

    static func format(date: Date) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = "MM-dd-yyyy HH:mm"
        return formatter.string(from: date)
    }
}
daspianist
  • 5,336
  • 8
  • 50
  • 94
  • Widgets are static you would have to setup the timeline so that you have the Widget refresh and on the refresh it would change its image. – Andrew Oct 06 '20 at 13:19
  • Thanks for this insight @Andrew. I looked at the Apple docs, but didn't find where I can control the refresh rate. Could I ideally refresh this as short as less than or at every 1 second? – daspianist Oct 06 '20 at 13:34
  • 1
    1 second would be quite fast for an image. It should be possible to do it every second as I have seen clock implementations in widgets. This question is per minute but I suppose it could be updated for every second https://stackoverflow.com/questions/64053733/updating-time-text-label-each-minute-in-widgetkit – Andrew Oct 06 '20 at 13:40
  • Great! Thanks for linking this as well. – daspianist Oct 06 '20 at 14:29

0 Answers0