How to Create a Square Grid Using SwiftUI

Ty Irvine
2 min readMar 18, 2021

I was searching around trying to figure out how to use grids in SwiftUI and there’s a lot of information about creating horizontal or vertical growing grids but there was no mention of square grids with even spacing between each element.

So I figured it out and wrote this article for any of you who were wondering how to do this.

Disclaimer: this may not be the best solution to this problem, it’s just the one I came up with.

A brief explanation of LazyVGrid, LazyHGrid, and GridItems

LazyVGrid & LazyHGrid work by using GridItems to dictate how many columns and rows to create when drawing out a grid.

LazyHGrid

As you can see a LazyHGrid behaves the same as a LazyVGrid it instead uses the GridItem spacing to space out each row added in. Then the spacing property spaces out the items in each row.

LazyHGrid Diagram

LazyVGrid

Like a LazyHGrid a LazyVGrid simply uses the GridItem spacing to space out each column added in. Then the spacing property spaces out the items in each column.

Achieving a square grid

So now that you have a good understanding of grids and how they work in SwiftUI I’ll explain how to make a grid with even spacing.

  1. First, we have to set the GridItem size property to be the same size as our object. In the case above you can see the squares have a height of 10 so the GridItem size would also need to be equal to .fixed(10) . This ensures no extra spacing is added in by the size property.
  2. Second, we need to make sure that the GridItem spacing and the LazyHGrid spacing property share the same value. This is the key to getting the evenly spaced look.

So as you can see it’s pretty simple. Here is an example below ⤵

I haven’t tested this snippet. I just wrote it out. It should work in a playground though.

Hopefully, that explains everything in a way that makes sense! If you have any questions feel free to ask.

(. ❛ ᴗ ❛.)

--

--