Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
SwiftUI Cookbook

You're reading from   SwiftUI Cookbook Discover solutions and best practices to tackle the most common problems while building SwiftUI apps

Arrow left icon
Product type Paperback
Published in Oct 2020
Publisher Packt
ISBN-13 9781838981860
Length 614 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Edgar Nzokwe Edgar Nzokwe
Author Profile Icon Edgar Nzokwe
Edgar Nzokwe
Giordano Scalzo Giordano Scalzo
Author Profile Icon Giordano Scalzo
Giordano Scalzo
Arrow right icon
View More author details
Toc

Table of Contents (15) Chapters Close

Preface 1. Chapter 1: Using the Basic SwiftUI Views and Controls 2. Chapter 2: Going Beyond the Single Component with Lists and Scroll Views FREE CHAPTER 3. Chapter 3: Viewing while Building with SwiftUI Preview 4. Chapter 4: Creating New Components and Grouping Views in Container Views 5. Chapter 5: Presenting Extra Information to the User 6. Chapter 6: Drawing with SwiftUI 7. Chapter 7: Animating with SwiftUI 8. Chapter 8: Driving SwiftUI with Data 9. Chapter 9: Driving SwiftUI with Combine 10. Chapter 10: Handling Authentication and Firebase with SwiftUI 11. Chapter 11: Handling Core Data in SwiftUI 12. Chapter 12: Cross-Platform SwiftUI 13. Chapter 13: SwiftUI Tips and Tricks 14. Other Books You May Enjoy

Using LazyHGrid and LazyVGrid (iOS 14+)

Just like lazy stacks, lazy grids use lazy loading to display content on the screen. They initialize only the subset of the items that would soon be displayed on the screen as the user scrolls. SwiftUI 2 introduced the LazyVGrid and LazyHGrid views. Let's implement a lazy grid that displays some text in this recipe.

Getting ready

Create a new SwiftUI iOS project and name it UsingLazyGrids.

How to do it…

We'll implement a LazyVGrid and LazyHGrid view inside a Stack view so as to observe both views in action on a single page. The steps are as follows:

  1. Above the ContentView struct's body variable, let's create an array of GridItem columns. The GridItem struct is used to configure the layout of LazyVGrid:
      let columns = [
        GridItem(.adaptive(minimum: 100))
      ]
  2. Create an array of GridItem rows that define the layout that would be used in LazyHGrid:
      let rows = [
           GridItem(.flexible()),
           GridItem(.flexible()),
           GridItem(.flexible())
      ]
  3. Create an array of colors. This will be used for styling some items in our view:
    let colors: [Color] = [.green,.red, .yellow,.blue]
  4. Replace the initial Text view in the body view with a VStack component and a scroll view.
  5. Within the scroll view, add a LazyVGrid view and a ForEach struct that iterates over the numbers 1999 and displays the number in a Text view:
     VStack {
       ScrollView {
        LazyVGrid(columns: columns, spacing:20) {
         ForEach(1...999, id:\.self){ index in
          Text("Item \(index)")
         }
        }
       }
     }
  6. The resulting view displays the numbers in a grid, but the content looks very bland. Let's add some zest by styling the text.
  7. Add a padding() modifier, a background modifier that uses the value of the current index to pick a color from our color array, and the clipshape() modifier to give each Text view a capsule shape:
    …
    ForEach(1...999, id:\.self){ index in
             Text("Item \(index)")
             .padding(EdgeInsets(top: 30, leading: 15,             bottom: 30, trailing: 15))
             .background(colors[index % colors.count])
              .clipShape(Capsule())
              }
    …
  8. Now, let's add a scroll view and LazyHStack. You will notice that everything else is the same as the LazyVGrid view except for the column parameter that's changed to a row parameter:
    VStack {
             …
              ScrollView(.horizontal) {
               LazyHGrid(rows: rows, spacing:20) {
                ForEach(1...999, id:\.self){ index in
                 Text("Item \(index)")
                      .foregroundColor(.white)
                      .padding(EdgeInsets(top: 30, leading:                     15, bottom: 30, trailing: 15))
                      .background(colors[index % colors.                     count])
                      .clipShape(Capsule())
                        }
                    }
                }
            }

    The resulting preview should look as follows:

Figure 2.13 – The UsingLazyStacks app

Figure 2.13 – The UsingLazyStacks app

Run the app in the preview and vertically scroll through LazyVGrid and horizontally scroll through LazyHGrid. Observe how smoothly the scrolling occurs despite the fact that our data source contains close to 2,000 elements. Scrolling stays responsive because all our content is lazily loaded.

How it works…

One of the fundamental concepts of using lazy grids involves understanding how to define the LazyVGrid columns or the LazyHGrid rows. The LazyVGrid column variable was defined as an array containing a single GridItem component but causes three rows to be displayed. GridItem(.adaptive(minimum: 80)) tells SwiftUI to use at least 80 units of width for each item and place as many items as it can along the same row. Thus, the number of items displayed on a row may increase when the device is changed from portrait to landscape orientation, and vice versa.

GridItem(.flexible()), on the other hand, fills up each row as much as possible:

let rows = [
        GridItem(.flexible()),
        GridItem(.flexible()),
        GridItem(.flexible())
    ]

Adding three GridItem(.flexible()) components divides the available space into three equal rows for data display. Remove or add more GridItem(.flexible()) components to the row array and observe how the number of rows decreases or increases.

We provide two parameters to our lazy grids: a columns/rows parameter that specifies the layout of the grid and a spacing parameter that defines the spacing between the grid and the next item in the parent view.

You have been reading a chapter from
SwiftUI Cookbook
Published in: Oct 2020
Publisher: Packt
ISBN-13: 9781838981860
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image