How to have a dynamic List of Views using SwiftUI

后端 未结 8 2022
被撕碎了的回忆
被撕碎了的回忆 2020-12-05 02:44

I can do a static List like

List {
   View1()
   View2()
}

But how do i make a dynamic list of elements from an array? I tried the followin

8条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-05 03:00

    I found a little easier way than the answers above.

    Create your custom view.

    Make sure that your view is Identifiable

    (It tells SwiftUI it can distinguish between views inside the ForEach by looking at their id property)

    For example, lets say you are just adding images to a HStack, you could create a custom SwiftUI View like:

    struct MyImageView: View, Identifiable {
        // Conform to Identifiable:
        var id = UUID()
        // Name of the image:
        var imageName: String
    
        var body: some View {
            Image(imageName)
                .resizable()
                .frame(width: 50, height: 50)
        }
    }
    

    Then in your HStack:

    // Images:
    HStack(spacing: 10) {
        ForEach(images, id: \.self) { imageName in
            MyImageView(imageName: imageName)
        }
        Spacer()
    }
    

提交回复
热议问题