Reader small image

You're reading from  SwiftUI Cookbook - Third Edition

Product typeBook
Published inDec 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781805121732
Edition3rd Edition
Languages
Tools
Concepts
Right arrow
Author (1)
Juan C. Catalan
Juan C. Catalan
author image
Juan C. Catalan

Juan C. Catalan is a software engineer with more than 18 years of professional experience. He started mobile development back in the days of iOS 3. Juan has worked as a professional iOS developer in many industries, including medical devices, financial services, real estate, document management, fleet tracking and industrial automation. He has contributed to more than 30 published apps in the App Store, some of them with millions of users. Juan gives back to the iOS development community with technical talks, mentoring developers, reviewing technical books and now as a book author. He lives in Austin, Texas, with his wife Donna, where they spend time with their kids.
Read more about Juan C. Catalan

Right arrow

Creating editable collections

Editing lists has always been possible in SwiftUI but before WWDC 2021 and SwiftUI 3, doing so was very inefficient because SwiftUI did not support binding to collections. Let's use bindings on a collection and discuss how and why it works better now.

Getting ready

Create a new SwiftUI project and name it EditableListsFields.

How to do it…

Let's create a simple to-do list app with a few editable items. The steps are as follows:

  1. Add a TodoItem struct below the import SwiftUI line:
struct TodoItem: Identifiable {
    let id = UUID()
    var title: String
}
  1. In our ContentView struct, let's add a collection of TodoItem instances:
    @State private var todos = [
        TodoItem(title: "Eat"),
        TodoItem(title: "Sleep"),
        TodoItem(title: "Code")
    ]
  1. Replace the body content with a List that displays the collection of todo items in a TextField view, which will allow for editing the...

Using searchable lists

List views can hold from one to an uncountable number of items. As the number of items in a list increases, it is usually helpful to provide users with the ability to search through the list for a specific item without having to scroll through the whole list. In this recipe, we'll introduce the searchable(text:placement:prompt:) modifier, which marks the view as searchable and configures the display of a search field, and discuss how it can be used to search through items in a list.

Getting ready

Create a new SwiftUI project and name it SearchableLists.

How to do it…

Let's create an app to search through different types of food. The steps are as follows:

  1. Add a new Swift file to the project called Food, which will contain the data used for the project. We use a struct to model different types of food. The struct has two properties, a String with the name of the food, and a category, which is an enum representing the type of food:
struct Food...

Using searchable lists with scopes

In this recipe, we will improve our searchable list with the addition of the searchScopes(_:activation:_:) modifier, which allows us to narrow the scope of our searches.The scope modifier could be useful to further reduce the scope of our search and reduce the time it takes to find an item. In our case, we have a list of food items, belonging to three different categories: meat, fruit, and vegetables. Selecting a specific scope narrows the search and gives the user a quicker way of finding the desired item.

This new modifier was introduced in iOS 16.4 and it is a nice mid-cycle addition, introduced with a minor version update of iOS. Most of the updates to iOS are usually announced in June, during the WWDC conference, and then introduced in September when the new version of iOS is released to users. However, Apple also releases new features during the year as is the case for the one we are using in this recipe.

Getting ready

In this recipe, we will...

Displaying tabular content with LazyHGrid and LazyVGrid

Like lazy stacks, lazy grids also use lazy loading to display a collection of items. They only initialize a subset of items that will soon be displayed on the screen when the user scrolls. You can display content from top to bottom using a LazyVGrid view and from left to right using a LazyHGrid view.

In this recipe, we’ll use the LazyVGrid and LazyHGrid views to display an extensive range of numbers embedded in colorful circles.

Getting ready

Create a new SwiftUI app called LazyGrids.

How to do it…

We’ll use a ForEach structure count for numbers from 0 to 999 and display them in a LazyHGrid, then repeat similar steps to display the numbers in a LazyVGrid view. The steps are as follows:

  1. In the ContentView struct, just above the body variable, create an array of GridItem columns. The GridItem struct helps configure the layout of the lazy grid:
    let columnSpec = [
         ...

Scrolling programmatically

In iOS 17, ScrollView received a series of improvements. One of these is the scrollPosition(id:) modifier, which associates a binding to be updated when the scroll view scrolls. The binding allows us to read the ID of the topmost or leading-most view shown in the scroll view at any given moment. We can also set the binding to the ID of our choice and the scroll view will scroll programmatically to show the chosen view.

If we are targeting previous versions of iOS, we must use ScrollViewReader to read the scroll position and to scroll programmatically. ScrollViewReader allows us to programmatically scroll to a different view in the scroll view, even if the view is not currently visible on the screen. For example, ScrollViewReader could be used to programmatically scroll to a newly added item, scroll to the most recently changed item, or scroll based on a custom trigger.

In this recipe, to showcase how to scroll programmatically, we will create an...

Displaying hierarchical content in expanding lists

An expanding list helps display hierarchical content in expandable sections. This expanding ability can be achieved by creating a struct that holds some information and an optional array of items. Let’s examine how expanding lists work by creating an app that displays the contents of a backpack.

Getting ready

Create a new SwiftUI project named ExpandingLists.

How to do it…

We’ll start by creating a Backpack struct that describes the properties of the data we want to display. The backpack will conform to the Identifiable protocol, and each backpack will have a name, an icon, an id, and some content of the Backpack type.

A struct that represents a backpack is good for demonstrating hierarchies because, in real life, you can put a backpack in another backpack. The steps for this recipe are as follows:

  1. At the top of our ContentView.swift file, before the ContentView struct, define the...

Using disclosure groups to hide and show content

DisclosureGroup is a view that’s used to show or hide content based on the state of disclosure control. It takes two parameters: a label to identify its content and a binding that controls whether the content is visible or hidden. Let’s take a closer look at how it works by creating an app that shows and hides content in a disclosure group.

Getting ready

Create a new SwiftUI project and name it DisclosureGroups.

How to do it…

We will create an app that uses the DisclosureGroup view to view some planets in our solar system, continents on Earth, and some surprise text. The steps are as follows:

  1. Below the ContentView struct, add a state property called showplanets:
    struct ContentView: View {
      @State private var showplanets = true
      // the rest of the content here
    }
    
  2. In the ContentView struct, replace the content of the body variable with a VStack and a DisclosureGroup...

Creating SwiftUI widgets

Apple provides the WidgetKit framework to show glanceable and relevant content from an app as widgets in iOS and macOS and complications on watchOS. Examples of the most popular widgets are Apple’s weather and stock apps.

There are two kinds of widget configuration options. StaticConfiguration is used for widgets with no user-configurable properties, such as stock market apps, while IntentConfiguration is used for apps with user-configurable properties, such as static widgets and intent widgets. StaticConfiguration widgets are not customizable, while IntentConfiguration widgets can be customized.

In this recipe, we’ll create a static widget that displays a list of tasks sorted by priority. Each task will be displayed for 10 seconds to give the user enough time to complete the task (we are assuming the user has super speed and can do everything in 10 seconds).

Getting ready

Download this project from GitHub: https://github.com...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
SwiftUI Cookbook - Third Edition
Published in: Dec 2023Publisher: PacktISBN-13: 9781805121732
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.
undefined
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 $15.99/month. Cancel anytime

Author (1)

author image
Juan C. Catalan

Juan C. Catalan is a software engineer with more than 18 years of professional experience. He started mobile development back in the days of iOS 3. Juan has worked as a professional iOS developer in many industries, including medical devices, financial services, real estate, document management, fleet tracking and industrial automation. He has contributed to more than 30 published apps in the App Store, some of them with millions of users. Juan gives back to the iOS development community with technical talks, mentoring developers, reviewing technical books and now as a book author. He lives in Austin, Texas, with his wife Donna, where they spend time with their kids.
Read more about Juan C. Catalan