从数组中显示带有名称的随机图像。 (斯威夫特用户界面)

Show random images with their names from an array. (SwiftUI)

swiftUI 的新手,我需要通过按钮操作随机显示图像及其名称。每次用户点击 contentView 文件中的按钮时,我应该如何调用图片数组以显示随机图片?

这是我要在 contentView 中随机显示的图片数组(放在 Assets 文件夹中的图片):

struct aPicture: Identifiable {
    var id: Int
    var name: String
    var imageName: String
}


let pictures = [
    aPicture(id: 0, name: "1", imageName: "1"),
    aPicture(id: 1, name: "2", imageName: "2"),
    aPicture(id: 2, name: "3", imageName: "3"),
    aPicture(id: 3, name: "4", imageName: "4"),
    aPicture(id: 4, name: "5", imageName: "5"),
    aPicture(id: 5, name: "6", imageName: "6"),
]

你可以试试这个:

 struct ContentView: View {

    struct aPicture: Identifiable {
        var id: Int
        var name: String
        var imageName: String
    }

    @State var random : Int = 0


    let pictures = [
        aPicture(id: 0, name: "1", imageName: "1"),
        aPicture(id: 1, name: "2", imageName: "2"),
        aPicture(id: 2, name: "3", imageName: "3"),
        aPicture(id: 3, name: "4", imageName: "4"),
        aPicture(id: 4, name: "5", imageName: "5"),
        aPicture(id: 5, name: "6", imageName: "6"),
    ]

    var body: some View {
        VStack {
            HStack {
                Spacer()
                Text(pictures[self.random].name)
                    .background(Color.white)
                Spacer()
                Button("Next image") {
                    self.random = Int.random(in: 0..<self.pictures.count)
                }
                Spacer()
            }

            Image(pictures[self.random].imageName)
            .resizable()
            .scaledToFit()
        }
    }
}

我建议您采用不同的方法。 1) 可以直接生成随机元素

let picture = pictures.randomElement() ?? default_if_empty_collection

2) 用户希望点击后看到不同的图片,这不可能是真的。 "store" 中的图片较少,更有可能随机生成相同的图片(可能看起来像 "nothing happens on tap")

下一个片段展示了如何解决这个问题。每次点击用户都会看到不同的图片,即使我们的 collection.

中只有树图片
import SwiftUI

struct ContentView: View {
    @State var img  = Image(systemName: "questionmark.square.fill")
    let imgs = [Image(systemName: "trash"),
                Image(systemName: "trash.fill"),
                Image(systemName: "trash.slash"),

    ]

    var body: some View {
        img
            .resizable()
            .scaledToFit()
            .frame(maxWidth: .infinity)
            .onTapGesture {
                var tmp: Image
                repeat {
                    tmp = self.imgs.randomElement() ?? self.img
                } while tmp == self.img
                self.img = tmp
        }
    }
}

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