1

I am using WatchKit and SwiftUI to build an Apple Watch application. At the start of my struct, I am initialising a publishing Timer:

struct ContentView: View {
    @State var index: Int = 0
    let timer = Timer.publish(every: 0.2, on: .main, in: .default)

var body: some View {
    return AnyView(VStack{
    Image(uiImage: images[index])
         .resizable()
         .frame(width: 50, height: 50, alignment: .center)
         .onReceive(timer) { (_) in
            self.index = self.index + 1
            if self.index > images.count - 1 {
               self.index = 0
            }
            debugPrint(self.index)
         }

The images: [UIImage]! array is defined globally in another file (for now). The first image does get displayed immediately. Now neither the Image updates, nor do I see a debugPrint of self.index. To me this means that the timer never started?

Florian S
  • 552
  • 3
  • 15

2 Answers2

1

I forgot the add .autoconnect() to line 3:

let timer = Timer.publish(every: 0.2, on: .main, in: .default).autoconnect()
Florian S
  • 552
  • 3
  • 15
1

Putting your timer directly inside onReceive() should work:

struct ContentView: View {
    @State var index: Int = 0

var body: some View {
    return AnyView(VStack{
    Image(uiImage: images[index])
         .resizable()
         .frame(width: 50, height: 50, alignment: .center)
         .onReceive(Timer.publish(every: 0.2, on: .main, in: .default)) { (_) in
            self.index = self.index + 1
            if self.index > images.count - 1 {
               self.index = 0
    }
    debugPrint(self.index)
}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
JUsltop
  • 44
  • 2