UICollectionView and SwiftUI?

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

    Since I'm not using Catalina Beta, I wrote here my code you can run on Xcode 11 (Mojave) as a playground to take advantage of run-time compile and Preview

    Basically when u look for a grid approach u should take in mind that SwiftUI child View get ideal size parameter from parent view so they can auto-adapt based on their own content, this behavior can be overridden (do not confuse with swift Override directive) by forcing view to a specific size via .frame(...) method.

    In my opinion this make View behavior stable as well as the Apple SwiftUI framework has been correctly tested.

    import PlaygroundSupport
    import SwiftUI
    
    struct ContentView: View {
    
        var body: some View {
    
            VStack {
                ForEach(0..<5) { _ in
                    HStack(spacing: 0) {
                        ForEach(0..<5) { _ in
                            Button(action: {}) {
                                Text("Ok")
                            }
                            .frame(minWidth: nil, idealWidth: nil, maxWidth: .infinity, minHeight: nil, idealHeight: nil, maxHeight: .infinity, alignment: .center)
                            .border(Color.red)
                        }
                    }
                }
            }
        }
    }
    
    let contentView = ContentView()
    PlaygroundPage.current.liveView = UIHostingController(rootView: contentView)
    

提交回复
热议问题