如何在单击按钮时循环浏览图像

How To Cycle Through Images on Button Click

所以我在这上面花了很尴尬的时间,我来请求你拯救我的理智。我正在构建一个应用程序来对我的盲人和视障学生进行评估。在这个特定的部分,我们正在测试他们的色觉(是的,大多数被认为是“盲人”的人仍然有一些剩余的视力)。我希望能够点击屏幕(按钮)并循环显示我评估的 6 种颜色。我曾尝试使用 ForEach 语句,但最接近成功的结果是屏幕一半是红色,一半是黄色。颜色都保存为我的资产中的图像。我还尝试将其设置为具有 .infinity 宽度和高度的框架的矩形会在点击时改变颜色,但这更不成功。我知道这可能非常简单,但正如您现在所知道的那样……我不是这方面的老手。在此先感谢,这是我当前的代码:

import SwiftUI

struct colorChange: View {

@State private var images: [UUID] = []

    var body: some View {
        VStack {
            ForEach(1...6, id: \.self) { image in
                Image("yellow"); Image("green"); Image("blue"); Image("purple"); Image("orange"); Image("red")
            }
            Button(action: {
                self.images.append(UUID())
            }, label: {
                Text("").frame(maxWidth: .infinity, maxHeight: .infinity)
            })
        }
    }
}

struct colorChange_Previews: PreviewProvider {
    static var previews: some View {
        colorChange()
    }
}

您可以尝试这样的操作,使用资产中的图像名称和 2 个按钮循环浏览图像:

struct ColorChange: View {
    @State private var images: [String] = ["yellow", "green", "blue", "purple", "orange", "red"]
    @State private var imgNdx = 0
    
    var body: some View {
        VStack {
            Image(images[imgNdx])
                .frame(width: 333, height: 333) // adjust the size as desired
            
            HStack {
                Button("Next", action: {
                    if imgNdx < images.count-1 {
                        imgNdx += 1
                    }
                })
                
                Button("Previous", action: {
                    if imgNdx >= 1 {
                        imgNdx -= 1
                    }
                })
            }
        }.buttonStyle(.bordered)
    }
}

或者,如果您想点击图片

struct ColorChange: View {
    @State private var images: [String] = ["yellow", "green", "blue", "purple", "orange", "red"]
    @State private var imgNdx = 0
    
    var body: some View {
        Button(action: {
            if imgNdx < images.count-1 {
                imgNdx += 1
            }
        }, label: {
            Image(images[imgNdx]).frame(width: 333, height: 333) // adjust the size as desired
        })
    }
}