UICollectionView and SwiftUI?

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

    iOS 14 and XCode 12

    SwiftUI for iOS 14 brings a new and nativ grid view that is easy to use, its called LazyVGrid: https://developer.apple.com/documentation/swiftui/lazyvgrid

    You can start with defining an array of GridItem's. GridItems are used to specify layout properties for each column. In this case all GridItems are flexible.

    LazyVGrid takes an array of GridItem's as its parameter and displays the containing views according to the defined GridItems.

    import SwiftUI
    
    struct ContentView: View {
        
        let columns = [
            GridItem(.flexible()),
            GridItem(.flexible()),
            GridItem(.flexible()),
            GridItem(.flexible())
        ]
        
        var body: some View {
            ScrollView {
                LazyVGrid(columns: columns) {
                    ForEach(0...100, id: \.self) { _ in
                        Color.orange.frame(width: 100, height: 100)
                    }
                }
            }
        }
    }
    

提交回复
热议问题