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

Adding SwiftUI to a legacy UIKit app

In this recipe, we will learn how to navigate from a UIKit view to a SwiftUI view while passing a secret text to our SwiftUI view. This recipe assumes prior knowledge of UIKit and it is most useful to developers who want to integrate SwiftUI into a legacy UIKit app. If this is not your case, feel free to skip to the next recipe. We'll be making use of a UIKit storyboard, a visual representation of the UI in UIKit. The Main.storyboard file is to UIKit what the ContentView.swift file is to SwiftUI. They are both the default home views that are created when you start a new project.We start off this project with a simple UIKit project that contains a button.

Getting ready

Get the following ready before starting out with this recipe:

  1. Clone or download the code for this book from GitHub: https://github.com/PacktPublishing/SwiftUI-Cookbook-3rd-Edition-/tree/main/Chapter01-Using-the-basic-SwiftUI-Views-and-Controls/10-Adding-SwiftUI-to-UIKit.
  2. Open the...

Exploring more views and controls

In this section, we introduce some views and controls that did not clearly fit in any of the earlier created recipes. We'll look at the ProgressView, ColorPicker, Link, and Menu views.ProgressView is used to show the degree of completion of a task. There are two types of ProgressView: indeterminate progress views show a spinning circle till a task is completed, while determinate progress views show a bar that gets filled up to show the degree of completion of a task. ColorPicker views allow users to select from a wide range of colors, while Menu views present a list of items that users can choose from to perform a specific action.

Getting ready

Let's start by creating a new SwiftUI project called MoreViewsAndControls.

How to do it…

Let's implement some views and controls in the ContentView.swift file. We will group the controls in Section instances in a List view. Section allows us to include an optional header. The steps are...

Using scroll views

You can use SwiftUI scroll views when the content to be displayed cannot fit in its container. Scroll views create scrolling content where users can use gestures to bring new content into the section of the screen where it can be viewed. Scroll views are vertical by default but can be made to scroll horizontally or vertically.

In this recipe, we will learn how to use horizontal and vertical scroll views.

Getting ready

Let’s start by creating a SwiftUI project called WeScroll.

Optional: If you don’t have it yet, download the San Francisco Symbols (SF Symbols) app here: https://developer.apple.com/sf-symbols/.

As we mentioned in Chapter 1, Using the Basic SwiftUI Views and Controls, SF Symbols is a set of over 5,000 symbols provided by Apple at the time of this writing.

How to do it…

Let’s learn how scroll views work by implementing horizontal and vertical scroll views that display SF symbols for alphabet characters...

Creating a list of static items

List views are like scroll views in that they are used to display a collection of items. However, List views are better for dealing with larger datasets because they do not load the entirety of the datasets in memory.

When we refer to a list of static items, we mean that the information that the list displays is predetermined in our code, and it does not change when the app is running. A good example of this use is the iOS settings app, where we have a list of settings that are fixed by the iOS version. Every time we run the settings app, we see the same list, its content, is static.

In contrast, a list of dynamic items has its content determined every time the app runs. As such, the app needs to accommodate any number of items in the list. One well-known example is the iOS mail app, where we have a list of our latest emails. The content of this list changes every time we run the app, making its content dynamic.

In this recipe, we will...

Using custom rows in a list

The number of lines of code required to display items in a List view row could vary from one to several lines of code. Repeating the code several times or in several places increases the chance of an error occurring and potentially becomes very cumbersome to maintain. One change would require updating the code in several different locations or files.

A custom list row can be used to solve this problem. This custom row can be written once and used in several places, thereby improving maintainability and encouraging reuse.

Let’s find out how to create custom list rows.

Getting ready

Let’s start by creating a new SwiftUI app named CustomRows.

How to do it…

We will reorganize the code in our static lists to make it more modular. We’ll create a separate file to hold the WeatherInfo struct, a separate SwiftUI file for the custom view, WeatherRow, and finally, we’ll implement the components in the ContentView...

Adding rows to a list

The most common actions users might want to be able to perform on a list include adding, editing, and deleting items.

In this recipe, we’ll go over the process of implementing those actions on a SwiftUI list.

Getting ready

Create a new SwiftUI project and call it ListRowAdd.

How to do it…

Let’s create a list with a button at the top that can be used to add new rows to the list. The steps are as follows:

  1. Create a state variable in the ContentView struct that holds an array of numbers:
    @State var numbers = [1,2,3,4]
    
  2. Replace the content of the body property of the ContentView struct with a NavigationStack containing a List view:
    NavigationStack {
       List{
           ForEach(self.numbers, id:\.self){
              number in
              Text("\(number)")
           }
       }
    }
    
  3. Add a .navigationTitle and a navigationBarTitleDisplayMode modifier to the list with a title and an...

Deleting rows from a list

So far, we’ve learned how to add new rows to a list. Now, let’s find out how to use a swipe motion to delete items one at a time.

Getting ready

Create a new SwiftUI app called ListRowDelete.

How to do it…

We will create a list of items and use the list view’s onDelete modifier to delete rows. The steps are as follows:

  1. Add a state variable to the ContentView struct called countries and initialize it with an array of country names:
        @State private var countries = ["USA", "Canada", "Mexico", "England", "Spain", "Cameroon", "South Africa", "Japan", "South Korea"]
    
  2. Replace the content of the body variable with a NavigationStack containing a List view that displays our array of countries. Also, include the onDelete modifier at the end of the ForEach structure:
            NavigationStack {
    ...

Creating an editable List view

Adding an edit button to a List view is very similar to adding a delete button, as seen in the previous recipe. An edit button offers the user the option to quickly delete items by clicking a minus sign to the left of each list row.

Getting ready

Create a new SwiftUI project named ListRowEdit.

How to do it…

The steps for adding an edit button to a List view are similar to the steps we used when adding a delete button. The process is as follows:

  1. Replace the ContentView struct with the following content from the DeleteRowFromList app:
    struct ContentView: View {
        @State private var countries = ["USA", "Canada", "Mexico", "England", "Spain", "Cameroon", "South Africa" , "Japan", "South Korea"]
        var body: some View {
            NavigationStack {
                List {
                    ForEach(countries, id: \.self) { country in...

Moving the rows in a List view

In this recipe, we’ll create an app that implements a List view that allows users to move and reorganize rows.

Getting ready

Create a new SwiftUI project named MovingListRows.

How to do it…

To make the List view rows movable, we’ll add a modifier to the List view’s ForEach struct, and then we’ll embed the List view in a navigation view that displays a title and an edit button. The steps are as follows:

  1. Add a @State variable to the ContentView struct that holds an array of countries:
        @State private var countries = ["USA", "Canada", "Mexico", "England", "Spain", "Cameroon", "South Africa" , "Japan", "South Korea"]
    
  2. Replace the body variable’s text view with a NavigationStack, a List, and modifiers for navigating. Also, notice that the .onMove modifier is applied to the ForEach...

Adding sections to a list

In this recipe, we will create an app that implements a static list with sections. The app will display a list of countries grouped by continent.

Getting ready

Let’s start by creating a new SwiftUI app in Xcode named ListWithSections.

How to do it…

We will add a Section view to our List to separate groups of items by section titles. Proceed as follows:

  1. (Optional) Open the ContentView.swift file and replace the body content with a NavigationStack. Wrapping the List in a NavigationStack allows us to add a title and navigation items to the view:
    NavigationStack {
    }
    
  2. Add a list and section to NavigationStack (or body view if you skipped the optional Step 1). Also, add a listStyle and navigationTitle and navigationBarTitleDisplayMode modifiers:
    List {
        Section(header: Text("North America")){
            Text("USA")
            Text("Canada")
            Text("Mexico...

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
    }
    
  2. 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")
        ]
    
  3. Replace the body content with a List that displays the collection...

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...

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...

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 €14.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