首页 > 解决方案 > 在SwiftUI中点击watchOS应用程序时如何更改图像

问题描述

点击时如何更改图像?

这是我的第一个 iOS 应用,更不用说手表应用了。我正在尝试构建一个简单的应用程序,当我点击图像时,它应该更改为下一个图像。到目前为止,我已经这样做了,并且正在显示第一张图像(test1),但是当我点击它时,什么也没有发生。


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()
  }
}

仅供参考,我正在为 Apple Watch 构建一个应用程序。

标签: iosxcodeswiftuiapple-watchwatchos

解决方案


您需要使用@State

struct ContentView: View {

  @State private var imgIndex: Int = 1

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

推荐阅读