How can I make grid layout as following in swiftUI?
I tried with LazyVStack & ZStack but not find properly as needed.
You can just use a series of nested HStack
s and VStack
s. 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:
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 VStack
s and HStack
s.