【问题标题】:SwiftUI: Using a ForEach to dynamically load ImagesSwiftUI:使用 ForEach 动态加载图像
【发布时间】:2021-06-02 19:14:48
【问题描述】:

我有一些图片的名称,例如 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)

            }

【问题讨论】:

    标签: swiftui swiftui-list


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 2018-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多