UICollectionView and SwiftUI?

后端 未结 16 1470
时光说笑
时光说笑 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:46

    Based on Will's answer i wrapped it all up in a SwiftUI ScrollView. So you can achieve horizontal (in this case) or vertical scrolling.

    It's also uses GeometryReader so it is possible to calculate with the screensize.

    GeometryReader{ geometry in
     .....
     Rectangle()
        .fill(Color.blue)
        .frame(width: geometry.size.width/6, height: geometry.size.width/6, alignment: .center)
     }
    

    Here is the a working example:

    import SwiftUI
    
    struct MaterialView: View {
    
      var body: some View {
    
        GeometryReader{ geometry in
    
          ScrollView(Axis.Set.horizontal, showsIndicators: true) {
            ForEach(0..<2) { _ in
              HStack {
                ForEach(0..<30) { index in
                  ZStack{
                    Rectangle()
                      .fill(Color.blue)
                      .frame(width: geometry.size.width/6, height: geometry.size.width/6, alignment: .center)
    
                    Text("\(index)")
                  }
                }
              }.background(Color.red)
            }
          }.background(Color.black)
        }
    
      }
    }
    
    struct MaterialView_Previews: PreviewProvider {
      static var previews: some View {
        MaterialView()
      }
    }
    

提交回复
热议问题