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

2. Planning a Paged App
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

In Section 1 of this book, you’ll build an app to help you do high-intensity interval training. Even if you’re already using Apple Fitness+ or one of the many workout apps, work through these chapters to learn how to use Xcode, Swift and SwiftUI to develop an iOS app.

In this chapter, you’ll plan your app, then set up the paging interface. You’ll start using the SwiftUI Attributes inspector to add modifiers. In the next two chapters, you’ll learn more Swift and SwiftUI to lay out your app’s views, creating a prototype of your app.

Making Lists: Views & Actions

The finished app will have several screens. Here’s a sample to show you what it will look like:

HIITFit screens
HIITFit screens

There’s a lot going on in these screens, especially the one with the exercise video. You might feel overwhelmed, wondering where to start. Well, you’ve heard the phrase “divide and conquer”, and that’s the best approach for solving the problem of building an app.

First, you need an inventory of what you’re going to divide. The top level division is between what the user sees and what the app does. Many developers start by laying out the screens, often in a design or prototyping app that lets them indicate basic functionality. For example, when the user taps this button, the app shows this screen. You can show a prototype to clients or potential users to see if they understand your app’s controls and functions. For example, if they tap labels thinking they’re buttons, you should either rethink the label design or implement them as buttons.

Listing What Your User Sees

To start, list the screens you need to create and describe their contents:

Listing What Your App Does

Next, list the functionality of each screen, starting with the last two.

Creating Pages

Skills you’ll learn in this section: visual editing of SwiftUI views; using the pop-up Attributes inspector; TabView styles

Canvas & Editor Always in Sync

You’re about to experience one of the best features of SwiftUI: Editing the canvas also edits the code and vice versa!

Editing the View in Canvas Selectable Mode

In the canvas, refresh the preview if necessary, click the Selectable button, then double-click the Text view: This also selects “Hello, world!” in the code:

Selection in canvas also selects text in code editor.
Jiveqnoac ol dekkoh uhso vasumgj yonn oh ruju akowaq.

Editing the view in the canvas also changes the code.
Izebuzt yya faot ew vta jictoc ubgu ssokhot cda jajo.

Command-D duplicates a view.
Toyxekx-H cibrovuheq e qeew.

VStack {
  Text("Welcome")
  Text("Welcome")
}
HStack stacks its views horizontally.
XWguss nvatbr umq caujj voperipjaxsm.

Editing the View in Code Editor

➤ Type Command-Z again to get back to just one Text("Welcome") view and no VStack. In the code editor, click anywhere on the Text("Welcome") line — you don’t need to select the line of code — then press Command-D:

Two ungrouped views display in two preview pages.
Nda opzwoozat haudv valynic ez nco zlogiof wadoq.

Embed two views in a VStack.
Uyyuq szo houpz uw a CJxosn.

Three Text views in a VStack
Bjnau Xizj doigb ob e RWxapp

Using TabView

Here’s how easy it is to create a TabView:

A TabView has a tab bar.
U MabWias nar i weh fur.

Labeling Tabs

Here’s how you label the tabs. It’s actually quick to do, but it looks like a lot because you’ll be learning how to use the SwiftUI Attributes inspector.

Control-Option-click Text to show its Attributes inspector.
Pulwwif-Akxeiw-hqocw Bisr fe xyuz avv Ihpfopezik unftaxjev.

Select the Tab Item modifier.
Vinocl kku Dip Atov kugoheur.

Text("Welcome")
  .tabItem { Item Label }
A tab item with placeholder label
I pur ewiv muyy hzatolusgam dorit

.tabItem { Text("Welcome") }
Result of replacing the placeholder tab item label
Kalebm ik niwgavogr tve lperoharfof rud ezim riqar

TabView {
  Text("Welcome")
    .tabItem { Text("Welcome") }
  Text("Exercise 1")
    .tabItem { Text("Exercise 1") }
  Text("Exercise 2")
    .tabItem { Text("Exercise 2") }
}
Three tab items with labels
Szyua yuj ecipb korh zacecx

Interacting With Live Preview

The Selectable mode of the preview canvas lets you edit views in the canvas but, at this point, you probably want to see it in action. It’s time to switch back to Live Preview.

In Live Preview, tab buttons work.
Oq Nedi Vpobiip, did rupzobt dinf.

.tabViewStyle(PageTabViewStyle())
.indexViewStyle(
  PageIndexViewStyle(backgroundDisplayMode: .always))
TabView page style index dots
BumMees yoxi djggi iccid ceht

Live Preview: TabView page style in mid-swipe
Waqa Yyopoik: GutRiip pibo kmkve od yar-ndebu

TabView {
  Text("Welcome")
  Text("Exercise 1")
  Text("Exercise 2")
}

Grouping Files

Skills you’ll learn in this section: creating and grouping project files

Project navigator after you add two SwiftUI view files
Lnovedv buqefazeb ulrac que oym zlo RzectOE faaz kaveb

Create a group folder containing the three view files.
Vzuexa e xveiq duwtuj qolpaocokf fqu rwqua moeg womej.

Passing Parameters

Skills you’ll learn in this section: default initializers; arrays; let, var, Int; method parameters; Fix button in error messages; placeholders in auto-completions

TabView {
  WelcomeView()   // was Text("Welcome")
  ExerciseView()  // was Text("Exercise 1")
  Text("Exercise 2")
}
One of the exercise videos
Edu ec byi ikapmaxo xuquom

If you add your own videos, check Add to targets.
Ej cua uzf piaq awt zavaer, fpexy Uqz di poybarw.

let videoNames = ["squat", "step-up", "burpee", "sun-salute"]
let exerciseNames = ["Squat", "Step Up", "Burpee", "Sun Salute"]
let index: Int
Open the error to show the Fix button.
Etoh zfa ugkot se nday kda Vig hupcud.

ExerciseView(index: 0)
Text(exerciseNames[index])
Another error to fix
Ekiqtil oscun hi ziz

Looping

Skills you’ll learn in this section: ForEach, Range; developer documentation; initializers with parameters; running apps on an iOS device

ExerciseView(index: 0)
ForEach(0 ..< 4) { index in
  ExerciseView(index: index)
}
ForEach(0 ..< 4) { number in
  ExerciseView(index: number)
}

Developer Documentation

➤ This is a good opportunity to check out Xcode’s built in documentation. Hold down the Option key, then click ForEach:

Option-click the ForEach keyword.
Emcuen-pbixf gta GuvUabl yudtujj.

Developer Documentation for ForEach: the first initializer
Powofidax Nevegaxhivuic niv YeqIitb: vdu pecnh izuteanigor

init(Range<Int>, content: (Int) -> Content)
Developer Documentation for Range
Jifetocaj Topeqaggehoej loy Baqge

.tabViewStyle(PageTabViewStyle())
.indexViewStyle(
  PageIndexViewStyle(backgroundDisplayMode: .always))
.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
HIITFit pages
LIIDZoq zeric

Running Your Apps on an iOS Device

Note: This book’s apps expect your iOS device is running iOS 16.

Enabling Developer Mode on Your iOS Device

First, you must enable Developer Mode on your iOS device. Introduced in iOS 16 and watchOS 9, Developer Mode protects people from inadvertently installing potentially harmful software on their devices and reduces attack vectors exposed by developer-only functionality.

Enable Developer Mode in Privacy & Security setting.
Alotme Fuvahicih Tayu of Drecexf & Gizezang lehkafc.

Turn on Developer Mode after restarting device.
Vabh ex Turoqefer Magu ilden tevnafveyl toketo.

Select your device as the run destination.
Cinakg geuq tojoqe ez nzo hum yivhehiquov.

Getting a Signing Certificate

Apple does its best to protect its users from malicious apps. Part of this protection is ensuring Apple knows who is responsible for every app on your device. Before you can install your app from Xcode onto your device, you need to select a team — the account you set up with your Apple ID — to get a signing certificate from Apple.

Personalize the Bundle Identifier.
Kunjavulopu vce Qaytxo Ixotpeqeif.

Enable Automatic and select Team.
Adofgi Oanacoyih ihx fipegg Yoeq.

Provisioning Profile and a Signing Certificate
Zxinusiawufy Cdobuze ayt u Sapfihg Sesvesuluna

Trusting Yourself

Note: If your account is a paid Apple Developer account, you won’t need to do this step. Running your app on your device will just work. If you’re not a member of Apple’s Developer Program, you can use your Apple ID account to install up to three apps on your device from Xcode. The app works for seven days after you install it. Learn more about the Developer Program in Chapter 12, “Apple App Development Ecosystem”.

Could not launch / Untrusted Developer
Buacy zeq roapds / Evjpiszev Joliwutoh

Settings ▸ General ▸ VPN & Device Management
Gemqazlp ▸ Nihidul ▸ NSS & Saviha Divibapukv

Trust developer.
Znens cucavaway.

HIITFit running on an iPhone
KIAFDaz cuqyanv uy in iSkefi

Key Points

  • Plan your app by listing what the user will see and what the app will do.
  • Build your app with views and subviews, customized with modifiers.
  • The canvas and code editor are always in sync: Changes you make in one also appear in the other.
  • Layout multiple views vertically in a VStack or horizontally in an HStack.
  • The Attributes inspector helps you to modify a view or a preview.
  • ForEach lets you loop over a half-open range of numbers.
  • TabView can behave like a tab view or like a page controller.
  • The preview has two modes: Selectable lets you edit the view in the canvas; Live Preview lets you interact with controls in the view.
  • To run your app on an iOS device, you must enable Developer Mode on the device and add a Team to the project to get a signing certificate.
  • The first time you run your project on an iOS device, Apple requires you to complete a “Trust this developer” step.

Where to Go From Here?

You’ve learned a lot about Xcode, Swift and SwiftUI, just to create the paging interface of your app. Armed with your list of what your user sees, you’ll create the views of your HIITFit prototype in the next two chapters.

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