0

How do I change the image when it is tapped?

This is my first iOS app, let alone a watch app. I'm trying to build a simple application, when I tap on the image, it should change to the next image. So far I have done this, and the first image (test1) is being shown, but when I tap on it, nothing happens.


import SwiftUI

struct ContentView: View {

  var body: some View {
    var imgIndex: Int = 1
    Image("test\(imgIndex)")
      .resizable(resizingMode: .stretch)
      .onTapGesture {
        imgIndex = 2
      }
  }
}

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    ContentView()
  }
}

FYI, I'm building an application for the Apple watch.

egeeke
  • 753
  • 1
  • 6
  • 18
imgkl
  • 1,013
  • 1
  • 7
  • 24

1 Answers1

1

You need to use @State:

struct ContentView: View {

  @State private var imgIndex: Int = 1

  var body: some View {
    
    Image("test\(imgIndex)")
      .resizable(resizingMode: .stretch)
      .onTapGesture {
        imgIndex = 2
      }
  }
}
egeeke
  • 753
  • 1
  • 6
  • 18
Dmytro Rostopira
  • 10,588
  • 4
  • 64
  • 86