SwiftUI was announced at WWDC 2019 and it paved a way for declarative programming for building interfaces. SwiftUI Grid comes in two different flavours, which includes LazyVGrid and LazyHGrid. As the name suggest, LazyVGrid is a Grid that flows in vertical direction and the LazyHGrid flows in horizontal direction.

If you are interested in videos then check out the following videos associated with this post.

Each Grid consists of GridItem, which dictates the structure of the cell displayed in the grid. GridItem can be fixedflexible or adaptive. Let’s start with the fixed size GridItems.

Fixed GridItems

var columns: [GridItem] = [

	        GridItem(.fixed(100)),
	        GridItem(.fixed(100)),
	        GridItem(.fixed(100))

	    ]

In the above code, we have created 3 fixed size columns of size 100. Now, we an easily use the LazyVGrid to create the columns and display information in the GridItem. This is shown below:

 NavigationView {

	            LazyVGrid(columns: columns) {

	                Rectangle()
	                    .fill(Color.red)
	                    .aspectRatio(contentMode: .fit)

	                Rectangle()
	                    .fill(Color.red)

	                Rectangle()
	                    .fill(Color.red)

	            }

	            .navigationTitle("LazyVGrid")
	        }

As you can see that for the content of LazyVGrid, we have used Rectangle but you can use any View you desire.

You can add more Rectangles to the LazyVGrid by running a ForEach. A ForEach loop will return a type View with each iteration. The implementation is shown below:

 NavigationView {

	            ScrollView {
	            LazyVGrid(columns: columns) {

	                ForEach(1..<20) { _ in
	                    Rectangle()
	                        .fill(Color.red)
	                        .aspectRatio(contentMode: .fit)
	                }

	            }}

	            .navigationTitle("LazyVGrid")
	        }

#ios-14 #ios-app-development #swift-programming #swiftui #programming

Understanding Grids in SwiftUI for iOS 14
13.10 GEEK