Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • SwiftUI Cookbook
  • Toc
  • feedback
SwiftUI Cookbook

SwiftUI Cookbook

By : Giordano Scalzo, Nzokwe
4.8 (10)
close
SwiftUI Cookbook

SwiftUI Cookbook

4.8 (10)
By: Giordano Scalzo, Nzokwe

Overview of this book

SwiftUI is an innovative and simple way to build beautiful user interfaces (UIs) for all Apple platforms, right from iOS and macOS through to watchOS and tvOS, using the Swift programming language. In this recipe-based book, you’ll work with SwiftUI and explore a range of essential techniques and concepts that will help you through the development process. The recipes cover the foundations of SwiftUI as well as the new SwiftUI 2.0 features introduced in iOS 14. Other recipes will help you to make some of the new SwiftUI 2.0 components backward-compatible with iOS 13, such as the Map View or the Sign in with Apple View. The cookbook begins by explaining how to use basic SwiftUI components. Then, you’ll learn the core concepts of UI development such as Views, Controls, Lists, and ScrollViews using practical implementation in Swift. By learning drawings, built-in shapes, and adding animations and transitions, you’ll discover how to add useful features to the SwiftUI. When you’re ready, you’ll understand how to integrate SwiftUI with exciting new components in the Apple development ecosystem, such as Combine for managing events and Core Data for managing app data. Finally, you’ll write iOS, macOS, and watchOS apps while sharing the same SwiftUI codebase. By the end of this SwiftUI book, you'll have discovered a range of simple, direct solutions to common problems found in building SwiftUI apps.
Table of Contents (15 chapters)
close

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.

bookmark search playlist download font-size

Change the font size

margin-width

Change margin width

day-mode

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Delete Bookmark

Modal Close icon
Are you sure you want to delete it?
Cancel
Yes, Delete