Building Grid Layout in SwiftUI

Mohammad Azam
Jun 11 · 2 min read

A grid is a simple structure which is used to display rows and cells. It is also a very common layout pattern to display data on the screen. Unfortunately, SwiftUI does not include a Grid layout.

Fortunately, with the help of List and stacks we can accomplish a simple Grid layout. In this post I will show you how to build a basic structure using a grid layout.

Implementation

The first thing we need is the data to be displayed in the grid. For the sake of simplicity we have already hardcoded the data which can be returned from a static function as shown below:

You can also use identified(by:..) function if you don’t want to conform to Identifiable.

Now, let’s go ahead and build the grid.

Grid is simply a List control of HStack views. Each HStack is configured to show two items (Image). The result is shown below:

In the above code you worked with Row and Cell structures but in real application you will be dealing with array of models. In order for the Grid to work for models you need to divide the array of models into smaller chunks., This will result in array of arrays. I have implemented an extension function on Array, which divides an array into specified chunks. The implementation is shown below:

Now you can utilize the chunked function as shown in the code below:

The final output is shown below:

If you liked this article and want to learn more about SwiftUI then check out my new course SwiftUI — Declarative Interfaces for any Apple Device below:

Mohammad Azam

Written by

iOS Developer, speaker and educator. Author of ARKit for iOS Developers and Mastering ARKit for iOS Udemy course. Lead instructor at DigitalCrafts.