Search code examples
iosswiftswiftuigridviewgrid

How to make specific grid layout in swiftUI


How can I make grid layout as following in swiftUI?

I tried with LazyVStack & ZStack but not find properly as needed.

enter image description here


Solution

  • You can just use a series of nested HStacks and VStacks. Make the views squares by aspectRatio(1, contentMode: .fit).

    struct ContentView: View {
        var body: some View {
            VStack {
                HStack {
                    ForEach(0..<4) { _ in Square() }
                }
                HStack {
                    VStack {
                        Square()
                        Square()
                    }
                    Square()
                    VStack {
                        Square()
                        Square()
                    }
                }
                HStack {
                    ForEach(0..<4) { _ in Square() }
                }
            }
            .aspectRatio(1, contentMode: .fit)
            .padding()
        }
    }
    
    struct Square: View {
        var body: some View {
            Rectangle().stroke()
                .aspectRatio(1, contentMode: .fit)
        }
    }
    

    Output:

    enter image description here

    In your screenshot, the squares seem to have a larger vertical spacing than horizontal spacing. That can be achieved by adding different (spacing: ...) parameters to VStacks and HStacks.