SwiftUI:使用 ForEach 动态加载图像

SwiftUI: Using a ForEach to dynamically load Images

我有一些图像的名称如 areavolume

我想用数据来驱动画面的显示。这是 places 可以是什么的示例:

   let places = {
      names: ["area", "volume"]
   }

我在下面尝试过类似的操作,但得到 Referencing initializer 'init(_:content:)' on 'ForEach' requires that 'String' conform to 'Identifiable'

    ForEach(places.name) { place in
        NavigationLink (destination: Any()) {
            HStack {
                Image(place)

            }

对于像 String 这样不直接符合 Identifiable 的类型,您可以告诉 ForEach 使用什么 属性 作为 id .通常使用 String,你会想要使用 .self(请注意,如果 String 不是唯一的,这会产生有趣的结果)。

struct Places {
    var names : [String]
}

struct ContentView : View {
    let places : Places = Places(names: ["area", "volume"])
    
    var body: some View {
        ForEach(places.names, id:\.self) { place in
                NavigationLink (destination: Text("Detail")) {
                    HStack {
                        Image(place)
                    }
                }
        }
    }
}