UICollectionView and SwiftUI?

后端 未结 16 1479
时光说笑
时光说笑 2020-12-02 07:32

How to create grid of square items (for example like in iOS Photo Library) with SwiftUI?

I tried this approach but it doesn\'t work:

var body: some          


        
16条回答
  •  一个人的身影
    2020-12-02 07:41

    Tired of finding many complicated solutions or Github libraries, I have decided to do my own, easy and beautiful Mathematical solution.

    1. Think you have an array of items var items : [ITEM] = [...YOUR_ITEMS...]
    2. You want to display an grid of Nx2

    When N is the number of ROWS and 2 is the number of COLUMNS

    1. To show all items you need to use two ForEach statements, one for columns and one for rows.

    Into both ForEach: (i) current index of ROWS, and (j) current index of COLUMNS

    1. Display the current item in the index [(i * 2) + j]
    2. Now let's go to the code:

    Note: Xcode 11.3.1

    var items : [ITEM] = [...YOUR_ITEMS...]
    var body: some View {
    VStack{
        // items.count/2 represent the number of rows
        ForEach(0..< items.count/2){ i in
            HStack(alignment: .center,spacing: 20){
                //2 columns 
                ForEach(0..<2){ j in
                   //Show your custom view here
                   // [(i*2) + j] represent the index of the current item 
                    ProductThumbnailView(product: self.items[(i*2) + j])
                }
            }
            }.padding(.horizontal)
        Spacer()
       }
    }
    

提交回复
热议问题