In the recent WWDC 2020, Apple introduced an LazyVGrid. You may think of it as a Vertical Scrolling Collection View.

A lot of the developers were finding that SwiftUI was missing the support of CollectionView when it was first introduced. With the release of LazyVGrid, you may now mimic the same behaviour as UICollectionView in UIKit.

A container view that arranges its child views in a grid that grows vertically, creating items only as needed

Apple Documentation

Prerequisites

To follow along this tutorial, you’ll need some basic knowledge in:

  • A basic familiarity with Swift.
  • At least Xcode 12+
  • Only supports iOS 14+

Getting Started With LazyVGrid

As you probably would have noticed that prefix of Lazy basically indicate that the view is only rendered when it appears on the screen which in turn boost performance. You don’t want to load all 1000 data at the same time, with LazyVGrid, you only load however many data that appear on the screen.

To make things more interesting, let’s make up a storyline. Tesla is having a competition to hire an iOS Engineer and they have open the submission for everyone. You love Tesla and you wanted to be part of the team.

So you decided to use SwiftUI and LazyVGrid to impress them.

You will first need to configure the layout and you can use GridItem to do that. GridItem basically let you configure the size and grid properties

var gridItems: [GridItem] = [GridItem()]

Next you will create LazyVGrid which is embedded inside ScrollView for scrolling purpose.

As you can see, the images stored inside Assets.xcassets are basically named as 1, 2, 3, 4…

NavigationView {
    ScrollView(.vertical) {
        LazyVGrid(columns: gridItems, alignment: .center, spacing: 20) {
            ForEach((1...6), id: \.self) { number in
                VStack {
                    Image(number.description)
                        .resizable()
                        .frame(width: UIScreen.main.bounds.width - 32, height: 200, alignment: .center)
                        .cornerRadius(24)
                        .scaledToFit()
                        .shadow(radius: 5)

                    Text("Model \(number)")
                }
            }
        }
    }
    .navigationTitle("Pick Your Tesla")
}

#swiftui #swift #xcode #ios #mobile-app-development

SwiftUI: LazyVGrid
2.50 GEEK