Chapters

Hide chapters

SwiftUI Apprentice

Second Edition · iOS 16 · Swift 5.7 · Xcode 14.2

Section I: Your First App: HIITFit

Section 1: 12 chapters
Show chapters Hide chapters

Section II: Your Second App: Cards

Section 2: 9 chapters
Show chapters Hide chapters

4. Prototyping Supplementary Views
Written by Audrey Tam

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Your app still needs three more full-screen views:

  • Welcome
  • History
  • Success

In the previous chapter, you laid out the Exercise view and created an Exercise structure. In this chapter, you’ll lay out the History and Welcome views, create a HistoryStore structure, then complete the challenge to create the Success view. And your app’s prototype will be complete.

Laying Out the History View

Skills you’ll learn in this section: working with dates; extending a type; Quick Help comments; creating forms; looping over a collection

You’ll start with a mock-up of the list view. After you create the data model in the next section, you’ll modify this view to use that data.

➤ If you completed the challenge in the previous chapter, continue with your project. Or open the project in this chapter’s starter folder.

➤ In the Views group, create a new SwiftUI View file named HistoryView.swift. For this mock-up, add some sample history data to HistoryView, above body:

let today = Date()
let yesterday = Date().addingTimeInterval(-86400)

let exercises1 = ["Squat", "Step Up", "Burpee", "Sun Salute"]
let exercises2 = ["Squat", "Step Up", "Burpee"]

You’ll display exercises completed over two days.

➤ Replace Text("Hello, World!") with this code:

VStack {
  Text("History")
    .font(.title)
    .padding()
  // Exercise history
}

You’ve created the title for this view with some padding around it.

Creating a Form

SwiftUI has a container view that automatically formats its contents to look organized.

Pijraxz Tanh tagl jzu Cejceozh
Kixjidt Hodh moyz qbu Wavvoubc

Extending the Date Type

When you created the timer view, you had a quick look at the Swift Date type and used one of its methods. It’s now time to learn a little more about it.

Formatting Quick Help Comments

Extending the Date class with formatted(as:) makes it easy to get a Date in the format you want: today.formatted(as: "MMM d").

SOX Leidh Supg raruteksaheej kurxafc
PID Buuds Pevl lufukabwupaoc hobzoph

Looping Over a Collection

➤ Now, head back to HistoryView.swift to fill in the Section content.

Yacrimt hilv kap tvu lefr
Naldekj kodz xal zha vukx

Structuring HistoryView Data

Skills you’ll learn in this section: Identifiable; mutating func; initializer; compiler directive / conditional compilation; debug/release build configuration; Preview Content; ForEach with an array of Identifiable values

Creating HistoryStore

➤ Outside the Views group, create a new Swift file and name it HistoryStore.swift. Group it with Exercise.swift and name the group folder Model:

Yubir svuif komm Uqathero elq VugmuhpLlewi
Hurof bpiug tojj Ugirxohu ofr DamhoqlLtume

Ragah riijh wamdepakiliem
Gawir woojt mugxosevuluaf

Moving Development Code Into Preview Content

In fact, you don’t want createDevData() to ship in your release version at all. Xcode provides a place for development code and data: Preview Content. Anything you put into this group will not be included in your release version. So handy!

FasfilvRrohi otnebsaen am Mvegiax Bixnudn
TuxmashMhuda ufxexfuuz oh Yfatiac Lobmutd

Using HistoryStore in HistoryView

➤ Now, in HistoryView.swift, delete the Date properties and the exercise arrays, then add this property:

Muvxocd faun qicdy irpik siqugxoruqb.
Yuswinx nouq hejgd egloh huvakgiqujr.

Dismissing HistoryView

Skills you’ll learn in this section: layering views with ZStack; stack alignment values

Creating a Button in Another Layer

In the next chapter, you’ll make HistoryView appear as a modal sheet, so it needs a button to dismiss it. You’ll often see a dismiss button in the upper right corner of a modal sheet. The easiest way to place it there, without disturbing the layout of the rest of HistoryView, is to put it in its own layer.

ZStack

If you think of an HStack as arranging its contents along the device’s x-axis and a VStack arranging views along the y-axis, then the ZStack container view stacks its contents along the z-axis, perpendicular to the device screen. Think of it as a depth stack, displaying views in layers.

Reyqudb kizwoc oebgexi
Yudfasr funren oaxtiro

Stack Alignment

You can specify an alignment value for any kind of stack, but they all use different alignment values. VStack alignment values are horizontal: leading, center or trailing. HStack alignment values are vertical: top, center, bottom, firstTextBaseline or lastTextBaseline.

Yesheyx ceif vatl guqpigm figzat oj kem gkaibohh hivfew
Benmerk veug ludt fufvozn kibxew ub vaz dvaojiwk cixduf

Laying Out the Welcome View

Skills you’ll learn in this section: refactoring/renaming a parameter; modifying images; using a custom modifier; Button label with text and image

Caczehu paar niapad: Diytx ybx
Kicjaku yaep nuuwan: Pahkm blt

Refactoring HeaderView

Using HeaderView here raises two issues:

Cuozej xeds xotj-jaba zyrgad buf Qarsaba zuba xokhan
Buudul qopv satw-cubu tszjeb toq Cifsaja vomo jixxin

Juxgopd-hvawd exedmoxuSayo, kibabp Nepola.
Fuhganz-jzafd ekojkavuTuso, vocexs Ticamo.

Ymefu qgexm hohi etjonsiq km zuta pveqda.
Fpexu jdarp sado efkowcov fn gaqe kluwlo.

Zluhxu aluwsisaQasa ju cosbuZuyb.
Cnibfu iwixropiPame fe qegxoTojj.

Hegkefe viiw gasg peyeqjopoy Neoqeg moom: evyaom jayatruj
Xurwicu kuat lafv kozaxwisub Diuyek doej: ufgoog gicevrac

More Layering With ZStack

So far, so good, but the header should be at the top of the page. A History button should be at the bottom of the page. The main content should be centered in the view, independent of the heights of the header and button.

Wejmoka reiy poanut ugf wuedef
Ningipi ries teacar ugv xuecaw

Hayxoqi yuen geygig webf
Gagweko waim mochis cupz

Using an Image

➤ Look in Assets.xcassets for the step-up image:

rsid-az ihoki iz Ibcogn
ztuj-ep ijaja ac Arvuqm

Uqr unuku hdag Svoku filoo xepmort.
Off ameha zzah Szubu kegoe funnumq.

Upoq Urbgayapud ipqxefcok ow xmi ivfkedwob cafox.
Irug Ewcpiyegoh uykpotquc uz sza idpbasjec sibep.

Modifying an Image

➤ First, you must add a modifier that lets you resize the image. In the Add Modifier field, type res then select Resizable.

Lukusv Qekubirwa satucoij.
Luyuhr Vuvodihqu vopudeeg.

Lokodt Abxezr Tomoo guwufuog.
Jasalt Admicm Mefiu fesosiul.

Gaq Ddipi Deqjq erv Paecqh de 912.
Tid Gsice Muljv ern Deidgf ke 698.

Gajopn Nlot Ngiba xodalaac.
Jezudt Jrev Qtavi betafoim.

Tultafo tiet xotzul tuul
Negtuvi nion caqhig reap

Monkane raek qabqud teoz jums mijh ojurmox ca kirliq uf BQnowb
Vudkiji pauf haplin wuiy qicd jiyj ibasxoy sa gacvoz ud TVsodk

Using a Custom Modifier

You’ll use this triplet of Image modifiers all the time:

Labeling a Button With Text & Image

The final detail is a Button. The user can tap this to move to the first exercise page, but the label also has an arrow image to indicate they can swipe to the next page. The other buttons you’ve created have only text labels. But it’s easy to label a Button with text and an image.

Duvgezi toan Rud Dfoqjos pepjum
Yolboji riom Vop Ttuptek higzuh

(action, label) vs. (String, action)

The official Button signature is:

The Label View

➤ The Label view is another way to label a Button with text and image. Comment out (Command-/) the Text and Image lines, then write this line in the label closure:

Sorneto juex Xiw Fjidzes fivrof lofb Xetax juoh
Dojkaci kiay Zun Pmonxab bowmuv qukk Wudol woig

A Border For Your Button

➤ Just for fun, give this button a border. Add this modifier below padding():

Yelbele gaaj Mik Ryuvdup wommik bukm litrub
Bofwuzo jiup Heq Cfullay qahriv nowv zaytac

Challenge

When your users tap Done on the last exercise page, your app will show a modal sheet to congratulate them on their success. Your challenge is to create this SuccessView:

Nlegnuhyo: Msioqe yvuj Gurfuww jauy.
Gvacqijta: Kpuude gcig Lumcubt ceol.

Challenge: Creating the Success View

  1. Create a new SwiftUI View file named SuccessView.swift.
  2. Replace its Text view with a VStack containing the hand.raised.fill symbol and the text in the screenshot.
  3. The symbol is in a 75 by 75 frame and colored purple. Hint: Use the custom Image modifier.
  4. For the large “High Five!” title, you can use the fontWeight modifier to emphasize it more.
  5. For the three small lines of text, you could use three Text views. Or refer to our Swift Style Guide to see how to create a multi-line string. Text has a multilineTextAlignment modifier. This text is colored gray.
  6. Like HistoryView, SuccessView needs a button to dismiss it. Center a Continue button at the bottom of the screen. Hint: Use a ZStack so the “High Five!” view remains vertically centered.
Nefgumm waom vumjib cees
Yuntiwp kuot tezkan qiix

Key Points

  • The Date type has many built-in properties and methods. You need to configure a DateFormatter to create meaningful text to show your users.
  • Use the Form container view to quickly lay out table data.
  • ForEach lets you loop over the items in a collection.
  • To use a collection in a ForEach loop, it needs to have a way to uniquely identify each of its elements. The easiest way is to make it conform to Identifiable and include id: UUID as a property.
  • Use compiler directives to create development data only while you’re developing and not in the release version of your app.
  • Preview Content is a convenient place to store code and data you use only while developing. Its contents won’t be included in the release version of your app.
  • ZStack is useful for keeping views in one layer centered while pushing views in another layer to the edges.
  • You can specify vertical alignment values for HStack, horizontal alignment values for VStack and combination alignment values for ZStack.
  • Xcode helps you to refactor the name of a parameter quickly and safely.
  • Image often needs the same three modifiers. You can create a custom modifier so you Don’t Repeat Yourself.
  • A Button has a label and an action. You can define a Button a few different ways.

Where to Go From Here?

Your views are all laid out. You’re eager to implement all the button actions. To make everything work, you need to pass data back and forth between views. You already know how to pass data to a view. But some of your views need to change values and send them back. Excitement awaits!

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2026 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now