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

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 app that displays...

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 Backpack struct:
struct Backpack...

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
}
  1. In the ContentView struct, replace the content of the body variable with a VStack and a DisclosureGroup view that contains two Text views with planet names...

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/PacktPublishing/SwiftUI-Cookbook...

Previewing a view with different traits

SwiftUI’s preview macro allows us to preview views with different traits. In this recipe, we will create a simple app that displays an image and some text, and we will preview it with different traits. This will allow us to have different variants of the view in the same canvas, switching among them by clicking on the preview buttons generated by Xcode.

Getting ready

Let’s create a SwiftUI app named PreviewingWithTraits.

How to do it…

We will modify the ContentView struct generated by Xcode and then add multiple preview macros to show the content with different traits. The steps are as follows:

  1. Open the ContentView.swift file and modify the body of the ContentView struct:
    struct ContentView: View {
        var body: some View {
            ZStack {
                Color.teal
                    .frame(width:200, height: 150)
                VStack {
                    Image(systemName: "globe")
       ...

Previewing a view on different devices

Xcode 15 allows us to preview our designs on multiple screen sizes and device types simultaneously, using the new device selector. In this recipe, we will create a simple app that displays an image and some text and preview it in multiple devices, without using any additional code.

Getting ready

Let’s create a SwiftUI app named PreviewOnDifferentDevices.

How to do it…

We will add an image and some text to the ContentView struct and then modify the preview to show the content on multiple devices. The steps are as follows:

  1. Download the friendship.jpg image from this chapter’s resources file at https://github.com/PacktPublishing/SwiftUI-Cookbook-3rd-Edition/blob/main/Resources/Chapter04/recipe3/friendship.jpg.
  2. Drag and drop the downloaded image file into the Assets folder in Xcode.
  3. Open the ContentView.swift file, and replace its content with the following code to display an image and some...

Using previews in UIKit

If you love the ease with which you can preview UI changes, but you are still working on UIKit projects, rest easy, as you can also use the canvas preview feature while building UIKit apps. With Xcode 15, the preview macros work with UIKit out of the box. Under the hood, Xcode adds the boilerplate code to wrap UIKit views and view controllers in SwiftUI views, so they can be previewed in the canvas.

In this recipe, we will learn how to preview a UIViewController and a UIView on the Xcode canvas.

Getting ready

Since this book is about SwiftUI and we are going to add previews to a UIKit app, we have already provided the UIKit app as a starter project, so you can focus on the preview functionality. It is very important that you clone or download the code for this chapter from GitHub, as explained in the Technical requirements section.

How to do it…

We will use the UIkit app provided and then add a couple of preview macros. The steps...

Using mock data for previews

So far, we’ve built apps using our own data. However, when dealing with large projects, data is usually obtained by making API calls. However, that can be time-consuming and quickly become a bottleneck for our previews. The better option is to make some mock data available for previews only. We can tell Xcode not to bundle the data and resources used for previews with our app when we submit the app to the App Store.

In this recipe, we will store some mock JavaScript Object Notation (JSON) data on insects in our Preview Content folder and fetch our data from the file, instead of making API calls. JSON is a lightweight format used to store and transfer data.

Getting ready

Create a new SwiftUI project called UsingMockDataForPreviews.

To get access to the files used here, clone/download this project from GitHub: https://github.com/PacktPublishing/SwiftUI-Cookbook-3rd-Edition/.

How to do it…

We will add a JSON file with...

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