Chapter 29
Building Grid Layouts Using LazyVGrid and LazyHGrid

The initial release of SwiftUI did not include a native collection view. You could either create your own solution or use third-party libraries. As SwiftUI continues to evolve, Apple introduces several new features for the SwiftUI framework, including two new UI components called LazyVGrid and LazyHGrid that address the need for grid views. LazyVGrid is for creating vertical grids, while LazyHGrid is for horizontal grids. As Apple mentions, the word 'Lazy' refers to the grid view not creating items until they are needed, which optimizes the performance of these grid views by default.

In this chapter, I will guide you on how to create both horizontal and vertical views using LazyVGrid and LazyHGrid. Both components are designed to be flexible, allowing developers to create various types of grid layouts with ease. We will also explore how to vary the size of grid items to achieve different layouts. Once we have covered the basics, we will delve into creating more complex layouts, such as the one shown in Figure 1.

Figure 1. Sample grid layouts
Figure 1. Sample grid layouts

The Essential of Grid Layout in SwiftUI

To create a grid layout, whether it's horizontal or vertical, here are the steps you follow:

  1. First, you need to prepare the raw data for presentation in the grid. For example, here is an array of SF symbols that we are going to present in the demo app:

To access the full content and the complete source code, please get your copy at https://www.appcoda.com/swiftui.

results matching ""

    No results matching ""