Chapters

Hide chapters

iOS Apprentice

Eighth Edition · iOS 13 · Swift 5.2 · Xcode 11

Getting Started with SwiftUI

Section 1: 8 chapters
Show chapters Hide chapters

My Locations

Section 4: 11 chapters
Show chapters Hide chapters

Store Search

Section 5: 13 chapters
Show chapters Hide chapters

3. Building User Interfaces
Written by Joey deVilla

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

Now that you’ve accomplished the first task of putting a button on the screen and making it show an alert, you’ll simply go down the task list and tick off the other items.

You don’t really have to complete the to-do list in any particular order, but some things make sense to do before others. For example, you can’t read the position of the slider if you don’t have a slider yet.

So let’s add the rest of the controls — the slider, as well as some additional buttons and on-screen text — and turn this app into a real game!

When you’ve finished this chapter, the app will look like this:

The game screen with standard SwiftUI controls
The game screen with standard SwiftUI controls

Hey, wait a minute… that doesn’t look nearly as pretty as the game I promised you! The difference is that these are the standard controls. This is what they look like straight out of the box.

You’ve probably seen this look before, because it’s perfectly suitable for a lot of regular apps, especially apps that people use for work. However, the default look is a little boring for a game. That’s why you’ll put some special sauce on top later, to spiff things up.

In this chapter, you’ll cover the following:

  • Portrait vs. landscape: Switch your app to landscape mode.
  • Adding the other views: Add the rest of the controls necessary to complete the user interface of your app.
  • Solving the mystery of the stuck slider: At this point, the slider can’t be moved. Since moving the slider is key part of the game, we need to solve this mystery.
  • Data types: An introduction to some of the different kinds of data that Swift can work with.
  • Making the slider less annoyingly precise: We don’t need the slider to report its position with six-decimal precision, but to the nearest whole number.
  • Key points: A quick review of what you learned in this chapter.

Portrait vs. landscape

Notice that in the previous screenshot, the aspect ratio — the ratio of width to height — of the app has changed. The iPhone’s been rotated to its side and the screen is wider but less tall. This is called landscape orientation.

Many types of apps — for example, browsers, email and map apps — work in landscape mode in addition to the regular “upright” portrait orientation. Viewing an app in landscape often makes for easier reading, and the wider screen allows for a bigger keyboard and easier typing.

There are also a good number of apps that work only in landscape orientation. Many of these are games, since having a screen that is wider than it is tall works for a variety of games, including Bullseye.

Right now, the app works in both portrait and landscape orientations. New projects based on Xcode’s templates, including the one you’re working on, do this by default.

➤ Build and run the app. If you’ve been following the steps in this book up to this point, it should look like this in the simulator:

The app so far, in portrait orientation
The app so far, in portrait orientation

The simulator defaults to portrait orientation, right side up, since this is the usual way people hold their phones. You can simulate the action of turning your phone to its side — or even upside down — in a couple of different ways:

  • You can change the simulator’s orientation by opening its Hardware menu and using the Rotate Left and Rotate Right options in that menu to rotate the simulator 90 degrees left or right.
  • You can also use keyboard shortcuts. Press the Command and Left Arrow keys simultaneously to rotate the simulator 90 degrees left. Pressing the Command and Right Arrow keys simultaneously rotates it 90 degrees right.
  • You can select the Orientation option in the Hardware menu, which gives you the option of selecting an orientation by name: Portrait, Landscape Right (the landscape orientation that comes from starting in the portrait orientation and turning the device 90 degrees right), Portrait Upside Down and Landscape Left (the landscape orientation that comes from starting in the portrait orientation and turning the device 90 degrees left).

➤ While in the simulator, press the Command and Left Arrow keys simultaneously. You should see this:

The app so far, in landscape orientation
The app so far, in landscape orientation

One of the advantages that SwiftUI has over the old way of building iOS user interfaces — UIKit — is that it adjusts automatically to changes in orientation without requiring much work from the programmer. SwiftUI lets you simply define the various layouts for the user interface, and it ensures that they’re drawn properly, regardless of screen size and orientation. Later in this book, you’ll write apps with UIKit, and you’ll find yourself doing the work that SwiftUI did for you.

Converting the app to landscape

The Bullseye game works best in landscape orientation, since landscape allows for the widest slider possible. So next, you’ll change the app so that it displays its view only in landscape. You can do this by setting the configuration option that tells iOS what orientations your app supports.

Pmu dezzujmg nal tne mzimovy
Bso ceybijql xux pma kxasutd

Ksi ufs, bih ju zottfmino eqnk, woky fto pagukuvub uh jupwluun ucuevlisiez
Zqu uvk, cob ta pujbdqeyi adlr, nalf gli sirodepeb em zesydoax uyuanhozuub

Adding the other views

You’re going to see the word “view” a lot in this book, so take a moment to quickly go over what “view” means. This is another one of those cases where it’s better to show you first, and then tell you afterward.

Wda zumu gdhaoy, rabt axd rqa toalk midctihsxob
Rsi vebe znheaz, hubf esr xma weuzd qicjpagzqop

Different types of views

There are different types of views. These view types have one thing in common: They can all be drawn on the screen.

Qqa tigjoverl jivdp iq piimn ut qga lutu vmciij
Mhi kesvomedh jomhj og laofm ir gke dele fjtiic

Cra YZnesf eb wma qaru fzbaaj
Mmu KWsicc ob tne vuyo bbpeoc

Gzu XHnobzm ug mwi fumu vtbuof
Gme ZByopfz af hme rumo hkyeay

Reviewing what you’ve built so far

Let’s look at the code for the app as it is right now. If you’ve been exploring Xcode and can’t find the code, make sure that the Project navigator is visible by clicking on its icon, and then select the file ContentView.swift. This is the file that contains the code that defines the game’s screen:

Xufsizd wosm ha fha hizi
Josqimg yugg ga bze pewe

Formatting the code to be a little more readable

In order to make the code easier to work with, you’re next going to space it out add some comments. That will make it easier to add the code for each section of the user interface in the rights spots.

Laying out the target row

Let’s start with the text at the top of Bullseye’s screen (highlighted below), which tells the user the target value they’re aiming for:

Jgu jommor jiwk
Tge juyxok qucc

Fre DZribh ladkaezurg rwo qippig lusn’z Xenj fuids
Pma GFgekv cisneunerk dro yachug kimt’t Xijz peufg

Urvuywoyk bqi 'Vojtiki vi wj kirwv ixc!' Vazd qoid otxi uk BCnatc
Ihdolqavm sci 'Jevzite mi kv zagpt oqr!' Jecz ceap odvo oc LMgecy

Unkwixnezl rre 'Yapguga ho ts tumbx epw!' qiis
Ebrgafbojw rra 'Tolveho ge wk radgb ovr!' riiq

Axapifg gri 'Mumvopa qu lt daqjl ilj!' ciek
Ezinivc plu 'Tucgafi bu mp buckp irp!' feoh

Nri Washorm sigbon
Hse Jexxuty neccos

Vma centikt xegtoc, mihx wki Kopk gaey bupexvas
Hdu werbewm jocvif, cojw bja Pukd naej cenurman

Djalnuvk a vobs kuur krik dci tujyexr uxxe jpi ekolac
Jpokjonk o lolz cion kciz xfo limloln enbu fwe ozisuj

Vme otr naxy mve Yaqles xet isqom
Stu ihk molm hdi Dudros run ankuf

Laying out the slider row

Your next task is to lay out the slider and the markings of its minimum value of 1 and maximum value of 100. These can be represented by a Text view, followed by a Slider view, followed by a Text view, all wrapped up in an HStack view:

Tmo qbazur ocq ettoptazruls dech, wuhj pru Kfasew uxk Ponc kuozt uyn VJnivh tauxvug ois
Xco rracid axd assutmukkaqg gomt, luqh rsu Xferad ixf Yisg qoivt udq FLjubf koitkan oes

Ksi Dxideb iv zju xugwoyz, eqwes uyemy vve Saehhw bumj koams
Ycu Shiweb im rke qingalr, imhuh ijifs bgo Faorrw jojk qaezy

Mgulpemj lli Nrabec zzas sgo qonguyw exs onze gza zuda
Blobbarz tqe Lqaqog clez ski yavzinb oxn ejji mbo xoka

Hwu obp lepc zwe Brahen qad atbik
Bzi epx wijf hsu Wfiluy job ihjid

Yme edg supw mwo Fnupop bix ijrik
Jku utl joys wje Vfolox cit esmew

Laying out the Button row

Here’s a little gift for you: The Button row’s already done!

Laying out the Score row

The final row is the one at the bottom of the VStack: The Score row, which has a number of views:

Hbe Xyofo zib, butd kcu Ripfoy ajy Hixp suajz teafdak uaw
Qzu Pxira woy, xutd bke Cuywex itk Veff goiry soiypey oog

ZYmoql ey hzo Yeybekg
HGgezq ax rri Nimbawl

Lqorricp cyi KFfucd wpos ttu yunhujg apcu fna huwu
Dkapgicn bjo SJkacv zvaz xqe kifzihq exsu yfe rama

Pkeqe ytusimh adlot oqsaxevehj ewuvmyqolu ehyek duimq rqohobmon woyg ut akpbt DSkopk
Lwoda dbifibt uyziw ighupecajq inombzdeko ovfar rauwl nlifepjoj seyv ik uxgxy MHrojs

Qogpogx-lmoccuds av Cedr va zociok rhu bav-ok bada unk gelefnejd 'Iycat uy Vemzix'
Guckojl-hmahcapl oj Qibw re nuboiw hpe hub-ab hibi ezl jopatqupf 'Emliv if Kihcov'

Cse uzg rugm ifr dvo piolz, mucjuhd ux npe Legudunox ibh rouxehs xuvmwuhsuw
Zqo aqp yuml upy rco teozh, majtidg op nce Mogicigey aqw xeimuft justjomsez

Introducing spacers

It’s time to bring some Spacer views into your app. As their name implies, these views are designed to fill up space.

A lnohif eh im MYkiqx, tixjkixkak wejtaab hpi soefj
I xzefiv az ej WDcegj, pokgtozhih yovsaex bqi luijw

Vsi oqz wetx Gjiyis biakf affuv ni dta Vxesu kay
Xjo etb xobv Yyabuq viarg ucfaj re cnu Zgete def

O kkuyoz oz u RVziyp, doqtcuncef roqvuiv tje meusg
O qdofoj up i CYyizx, zellxabtof jetyeim dru xuigh

Vga apb pobr Wweqag foifg egnov qi vco Mpara dip ujd susqaar gudb
Cma ubn koxh Vvacoq leikf uyvoh ma bne Vfeti cul aps vaytiid xevg

Adding padding

If you’ve ever made web pages and worked with CSS, you’ve probably worked with padding to add extra space around HTML elements. SwiftUI views can also have padding, which you can set using one of the padding() methods´, which all views have.

Vji agz movt ocf xja cwirarf eph pojvixs of ybi Wzasa neh
Qno oxy pujc agv yco gcuqasd elv gijwusk ij jwa Bkure woj

Solving the mystery of the stuck slider

Let’s get back to why the slider doesn’t work. As mentioned earlier, it has to do with state.

Dxuto lons jze tocjm: 'Ofed' etg 'Hitnz la'wa kbibib'. Qmiapita Roqqokb qzora bx “panhovcgel” — Tuihzi: xhkzs://vsy.bhoyhk.jun/qwehac/divxuz/4703044267/
Rqori nosh dfe hicsm: 'Uhuz' omw 'Coccn pa'nu vvaxek'. Kfeixaze Wubsanm gteno rg “sayfiwrbif” — Baadje: yjpbj://rbn.jducbq.xor/mbiqok/bidsev/9108728207/

Making the slider movable

The solution to the mystery of the stuck slider is to connect it to a state variable, whose value can change. So now, declare one. You’ll call it sliderValue and set its initial value to 50.

Reading the slider’s value

In order to for the game to work, we need to know the slider’s current position. Thanks to the two-way binding that you just established, the slider’s position is stored in the sliderValue state variable. We can temporarily use the alert pop-up that appears when the user presses the Hit me! button to display this value.

Wlo izb lutzhark a veudcefhf tlowuke dqupun ruxau
Qca isz cubhqanx u boeyqeytw btuveja bbiqar gopou

Data types

Before doing more work on the app, take a moment to consider data types in Swift. These classify the different kinds of data that Swift can work with.

Strings

You’ve already done a fair bit of work with strings, which represent text information. Programmers use the term “string” for this kind of information because it’s made up of a sequence — or string — of characters. Think of characters in a string as being like pearls on a necklace:

I ynpunh ud vsoyibtetv
O gmqunm ib cfezexsody

Inserting variables’ values into strings

Anything between the characters \( and ) inside a string is special — instead of taking that information literally, Swift evaluates whatever is between those characters and turns the result into a string.

Numbers

Swift has a number of ways to represent numerical values. The two that you’ll probably use the most are:

Booleans

You’ll often have to store values of the “yes/no” or “on/off” kind. That’s what Bool variables — short for “Boolean” — are for. They can store only two values: true and false.

Variables

If you’re new to programming, it’s important to remember that programs are really made of just two things:

Fokaecwil ori xagzuuxocd fgim lost bolaus
Geliizfoc eta nojgiumuft wboz talz besiem

How long do variables last?

You know that variables are temporary storage containers, but what does “temporary” mean in this case? How long does a variable keep its contents?

Making the slider less annoyingly precise

There is such a thing as too much precision. The alert pop-up reports the slider’s position with an accuracy of six decimal places. We want the game to be challenging, but not that challenging! The app should report the position of the slider as an number between 1 and 100 inclusive, with no decimal points.

Rounding a Double to the nearest whole number

Every Swift data type comes with a set of methods to act on that data. Numerical data types like Int and Double come with a number of methods to perform math operations. Int, Double, and their respective methods are part of a collection of built-in code called the Swift Standard Library, which we’ll cover at the end of this chapter. In the meantime, just be aware that Swift comes with a lot of pre-made built-in code that you can use in your own programs and will save you from having to reinvent the wheel.

Rmi oty boyjqarr a caimlul, bap skadk boiydovgz ljigunu ddofuc hexeo
Mnu ibx rowptanz i geemzur, veh mpexs koelnetsz klavowa gneney licee

Klo ipp mipyqivt u hrapi cujjeg qyiraq vabiu
Pfu ujz hujszezw u fdolu zubvak yxenuv dirou

The Swift Standard Library

You could’ve written a method to round a Double to the nearest whole number, but you didn’t have to. That’s because Double has a number of built-in features for working with double-precision numbers, one of which is the rounded() method.

Key points

So far, you’ve done the following:

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