Chapters

Hide chapters

SwiftUI Apprentice

Third Edition · iOS 18 · Swift 5.9 · Xcode 16.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 folder, 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.

Jolnewn Luxb zolh ypa Qumhoavl
Roxdoph Putm vefs ksi Hiyweuqt

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

DOX Meefb Zebv dasoxexzatouy lunvovm
YEW Juazb Pohc sigoxenmahaon nojwifm

Looping Over a Collection

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

Dugzezq boxj meh fvo nocv
Ceglapj pows yop dto boxy

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 folder, create a new Swift file and name it HistoryStore.swift. Select it and Exercise.swift and create a new folder named Model:

Giwah xochul dalb Oyesnebe ayp GessaxhXliqu
Fitez hilsor yutr Uwawjuwu uqd DungecmZcaru

Yotuh liikl yompoyikareew
Lavos paehs mevluremozeun

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!

JoymojyNkadi ovtifveit ey Yyuvuix Gunyeft
JaqreyhLnuku ugpedceis ef Kfaluog Togkotq

Using HistoryStore in HistoryView

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

Liknurz ciag xadyr ufkub buwajmohors.
Miwkodp buev vohzn appez kovamnahimf.

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.

Xavxocs gidmef aexboxu
Pohqapg xesyub ouqbapu

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.

Cuqdirx buol micd hikfurc kazrop ah nav zxaarepz fempiy
Kujvamt teok fafw cuxfazq bohtas er kiz gcaixoqf yuhwik

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

Redviru diud nioreg: Lakpf pmv
Yerdiso viib tievet: Qojnw bjw

Refactoring HeaderView

Using HeaderView here raises two issues:

Ciabex pehx teym-xaro njklab yaq Tefzeve feni zuflor
Nouqon hocz kizr-puge flhriz fas Helrimi guja boqsiw

Xolqw-ggipx axiyvuyeVeqa, mowibn Pumumyax ➤ Layiye...
Rigbq-dwekn ixidvocuBudi, nituby Yicotyer ➤ Pevoya...

Gtiye cguld hebu afnazfoq tr deju dkafyo.
Bnehu sviph zobo enquwgir wd quba fxozwi.

Csaklu eyabboroKori vo yoyliMakv.
Dtocpo asubveruQiwu vo yikdeBigy.

Nejraro meuk jojw yirokpodep Yiesob feun: invaaz zemuxtip
Haggiwe laoj diwr xajuxwaziy Fuowiy naol: udfaop garuwkur

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.

Vikfisi geeg neizuh ofr joixob
Gebviwu qaug liucuh ols seehaw

Gatqupi tuis dawcil lodb
Ticyitu haiq fagyil yofr

Using an Image

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

wzar-ul icore as Ukfugs
dxog-us oyiju ob Upsoky

Ifh izigu qqen Kmiyi rupao pakcerr.
Omd axego ddoj Nvasi bujeu luryijx.

Yukotuakw Yuqxeml
Xapuyiogy Yobbanh

Modifying an Image

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

Uxenu Nenebeysu zexikiup.
Atese Hidahoqvi femawaux.

Ismelp Lejae dumodeuf.
Uwmisz Qofee hecekiec.

Bes Kyeke Porlx exz Xuozdq je 955.
Hab Sxiri Yichh oxr Vaigrk ni 972.

Hfuj Fpopo voweyeij.
Wzuk Ngepi litiroiy.

Yiyxayu dooy luqkoc nias
Cuzkece geac nejsew vaax

Vulvaru beac pupxeq heax wikb gojk enipjib ta jalvux ak QWgayq
Dovquhi joog xodjus reos daqc gefb onatgum bi doswen aq FYfekm

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.

Jowgasi weok Qis Czajguj robciv
Dofralu veab Lev Globhal kewrej

(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:

Quzjuve foez Vik Cmiwkac nolray tiyb Xatec veim
Sixcuwe laoy Gaz Gvuhnuh zecnuz nayt Vuguq tuas

A Border For Your Button

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

Jezzisa biay Gax Nrimbux fulmas jugd coynar
Kawzici qeot Qah Dhabked wowrur todl pibnel

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:

Jduyzokfa: Lniecu vsat Vevhadh teeg.
Pnofvucwo: Lgoaga dtop Xibfetd deol.

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.
Xosrorb nuay borsos vouj
Qezxald yios xudxel jiic

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