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

Technical requirements

The code in this chapter is based on Xcode 15.0 and iOS 17.0. You can download and install the latest version of Xcode from the App Store. You'll also need to be running macOS Ventura 13.5 or newer. Simply search for Xcode in the App Store and select and download the latest version. Launch Xcode and follow any additional installation instructions that your system may prompt you with. Once Xcode has fully launched, you're ready to go.All the code examples for this chapter can be found on GitHub at https://github.com/PacktPublishing/SwiftUI-Cookbook-3rd-Edition/tree/main/Chapter05-Creating-new-Components-Grouping-views-in-Container-Views.

Showing and hiding sections in forms

Forms provide a means of getting information from the user. Users get discouraged when completing very long forms, yet fewer people submitting a form may mean less data for your surveys, fewer signups for your app, or fewer people providing whatever data you're collecting.In this recipe, we will learn how to show/hide the additional address section of a form based on the user's input.

Getting ready

Create a new SwiftUI project named SignUp.

How to do it…

We will create a signup form with sections for various user inputs. One of the sections, named Previous Address, will be shown or hidden based on how long the user has lived at their current address. The steps are given here:

  1. Create a new SwiftUI view called SignUpView:
    1. Press Command () + N.
    2. Select SwiftUI View.
    3. Click Next.
    4. Name the view SignUpView.
    5. Click Create.
  2. In SignUpView.swift, above the SignUpView struct declaration, define the new struct Address used to hold some data...

Disabling and enabling items in forms

Form fields may have additional requirements such as minimum text length or a combination of uppercase and lowercase characters. We may want to perform actions based on the user's input, such as disabling a Submit button until all requirements are met.In this recipe, we will create a sign-in view where the Submit button only gets enabled if the user enters some content in both the username and password fields.

Getting ready

Create a SwiftUI project called FormFieldDisable.

How to do it…

We will create a login screen containing a username, password, and a Submit button. We will disable the Submit button by default and only enable it when the user enters some text in the username and password fields. The steps are given here:

  1. Create a new SwiftUI view file named LoginView:
    1. Press Command () + N.
    2. Select SwiftUI View.
    3. Click Next.
    4. Enter LoginView in the Save as field.
    5. Click Create.
  2. Open the LoginView.swift file and add a @State variable...

Filling out forms easily using Focus and Submit

Filling out forms can be tedious if the user must manually click on each field, fill it out, and then click on the next field. An easier and faster way would be to use a button on the keyboard to navigate from one form field to the next.In this recipe, we will create an address form with easy navigation between the various fields.

Getting ready

Create a new SwiftUI project named FocusAndSubmit.Check the project's Build Settings and make sure the iOS target version is set to 15.0 or higher.

How to do it…

We add some text fields for various address fields within a VStack component and use @FocusState to navigate between them and submit the filled-out form at the end. The steps are given here:

  1. Open the ContentView.swift file and add an enum for the fields of an address:
struct ContentView: View {
    enum AddressField{
        case streetName
        case city
        case state
        case zipCode
    }
    // ...
}
  1. Below...

Creating multi-column lists with Table

macOS has supported multi-column tables for a long time. SwiftUI support for multi-column tables was added in macOS 12 with the Table struct, which, one year later, was added to iOS with the release of iOS 16. Table is a container that presents rows of data arranged in columns and provides the ability to sort the data by column and to select one or multiple rows of data. Table only supports the multi-column layout on the iPad, and it falls back to a one-column list on the iPhone, displaying, by default, the first column. In a similar way, column sorting and multiple-row selection are only available on the iPad.In this recipe, we will create an app that displays the top 20 US cities by population on the iPad screen using Table. We will incorporate sorting and multiple-row selection, and finally, create a custom layout to display the information on the iPhone.

Getting ready

Create a new SwiftUI project named MultiColumnTable.Check the project&apos...

Using Grid, a powerful two-dimensional layout

In Chapter 3, Exploring Advanced Components, we learned about LazyHGrid and LazyVGrid. These two container views provide an efficient way of drawing views in a two-dimensional layout. They are very efficient for a large set of embedded views because they only draw the displayed or about-to-be-displayed views. This efficiency comes with the limitation of having to specify the layout in one of the two dimensions explicitly. For example, in a LazyVGrid, we need to specify the layout for the columns. Once SwiftUI calculates the column width depending on the horizontal space available, the number of columns to be displayed gets fixed, and the embedded views get positioned in a grid with fixed columns and an unbounded number of rows. But what about if we wanted a view to span two columns? What about if we have a small set of views that we want to display in a two-dimensional layout, but we want full control of the alignment and spacing among them...

Displaying popovers

A popover is a view that can be displayed onscreen to provide more information about a particular item. It includes an arrow pointing to the location where it originates from. You can tap on any other screen area to dismiss the popover. Popovers are typically used on larger screens such as on the iPad.

In this recipe, we will create and display a popover on an iPad.

Getting ready

Create a new SwiftUI project named DisplayingPopovers.

How to do it…

Following the pattern we’ve used so far in this chapter, we will first create a @State variable whose value triggers the displaying or hiding of a popover. Then we will add a .popover() modifier that displays the popover when the @State variable is true. The steps are as follows:

  1. Just above the body variable in the ContentView.swift file, add a @State variable that will be used to trigger the display of the popover:
    @State private var showPopover = false
    
  2. ...

Creating context menus

A context menu is a pop-up menu used to display actions that the developer anticipates the user might want to take. SwiftUI context menus are triggered using the touch-and-hold gesture in iOS and iPadOS and a control click on macOS. Context menus consist of a collection of buttons displayed horizontally in an implicit VStack.

In this recipe, we will create a context menu to change the color of an SF Symbol.

Getting ready

Create a new SwiftUI project named DisplayingContextMenus.

How to do it…

We will display a light bulb in our view and change its color using a context menu. To achieve this, we’ll need to create a @State variable to hold the current color of the bulb and change its value within the context menu. The steps are as follows:

  1. Just above the body variable in ContentView.swift, add a @State variable to hold the color of the bulb. Initialize it to red:
    @State private var bulbColor = Color.red
    
    ...
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