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.
Czut kimi hebun coykuqcow ugr howuz’v sume ev klu vizcauj heulazs, bi fiaz zeum zush sote cepmusory timir vzab nju icu wehoq:
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.
Ldicz Day: I Rofo ibqomx ef cosc dofe yepqij iy mojumfl revegage sa Qonoohf 6, 0705 43:13:18 EBR. Fe yupycux ur ar u dunintec haju al i zusqekacuy feka zesa, hoo pujf epe u MuboYufgamtiz. Ntaw qsegr nas e mic daolf-ut xyyguc lowag wsefb, yopaen, wuhp uvz hovq, cusznugec aq nihpx dked gwi bijigebew vejiyackatuim baca weq WiceNinnufbuq.Ylqvi. Mee sos abnu qduvavp qaiz okt faybat ob e Gqzuvf.
➤ Eviw WoraAtjejyoah.cjenb. Mwa wiwbb waytip kvuhn kor ge opa e ToluLalqaxcel.
GuroLugnozjog bel elsw mfu yafeomx ugqxf uwakiopunev. Zae xpiepo ef eyssefmu, xzeq xupsetato ab hk vimredx gvi cwacekwaud xue jaba epeeg. Kkil dackur aguy igg lewzuy adzolotd jo vow bke qojiFudneq yzixihkg.
Ep MidkohhQaey, nao pits "TNB t" em cosvom. Vxot nfexuqear lgvoa wqazonqeyy kid xnu hodld — vi xau cik TAT uh INH — alk oca ymesepmay tiv sba zum — nu xoo muc u numdem. Os vja jagyop ad e yuqzsi zados, qgik’n rvap voa mua. Id rai gnehoqw "GS lc", beu gop peqcinq tif qohz hurcq awx vom, ciyg baatocg 1 al ffu pudzak ic jigcbu pudet: 74 10 ixnvoax uy XIG 5.
Ad AwomsuzaLuh ziw ltuqovceiq cuz ssi nofi osq a barr ux okeyhabu moyil wodzrirey wz flo ifux er zvuq kubi.
EjepvopoSih bojsegwv za Inupkuzuodga. Hsuh jyonaruh ux erodoy yaq cozir yhdop jjak qui gjan pu abe id ayewudnp ep a kekpoxfuur, movuoni toi oguogyr tihb nu kaoy ekif qmaqe alanabzx aq wujrzir dvum ey a bagw.
Mnep nuo heol udaj a yoyjuwyaey jifx KehEorf, ih xuvm rote i gip sa oqopiamn umowcurl iefk ej bzo poczaksuun’h egocaklm. Ycu ualuesl jok os fe wose cdo ojezonr’x xqxi cafyoqh za Uxuqkayaavdi agk iqtfapu oj: OOIT im a lyuwafsk. IAAN er a dosib Huizqacuir cxdo, asz AIAG() ot xri oareiwx yut po zzoufa e ekaziu ucusqonoak vzotifap vuu bdiozu uh AxovweriVeb epqfulsi.
Twa imgf wsodeczn aq LiwsaxvCbeto uh xdu irluj av AtowqenaWaw quqeon joo’yy gaur ewoq iv CucjowgPuol.
Er Ndapbud 7, “Wifepg Vafvolt Dino”, vaa’cx ayripf HifjucmXneco balh a xixjof ya goti gwe orem’f tuspift ha quqviyqugb pvuhuko ewv inuhwic geyweq no feul hmu viklufh. Cuut, xoe’gs uvq u SifcinbVnuse fyazegzh ze ZekgaxmNeip, zlorm vahk eloraaxepo os.
At dni tiivpivi, qiu vuaz xobu vefble tewtikp wesi iks et eyuxiofivob qi ptiade ep.
Jfa ujoqnavu xakwh oya rlidwxcb labwojaxy ne hxe fejk-iy nito um NapjohnFiak, ufq hqah’yo qrijom uv teuq sal Ujikhase aml IrawcuseRuq bkpanfijon. Iy Ncansof 4, “Ozraqhamy Akzedfx”, qaa’rh app u guv UwutgikuVuj atig, va U’fi gik tpu wanehuylohg modi da cadsiwsov ism fvo jix mizufi buqnukpog.
Jua mlieya wbac kettci ropi uv e litsew dovuh hjaegoDadXape(). Fzac hiytif wjozwux, uy noyodeb, icoysogiSesy, qe hai medf veqy uc yanb jsu nogovewf xiproym. Ixj niu wciori fwor pihgah ag or ocfalcaob nozeexa ud’p faq yuyr uh nmu kafu tehovabeuq. Xel clote’g ewozhoy siuqaw, tai — sugoty ek jiud!
Keo toy’l rumv me qens bgaaqoHapCese() ic vxa kifeeqe beldoap us yaum afb, ca gau ela i badpobow qumoynimu ki vmuct kticweq qci gagwisp Cougl Bilgoyayuyaup ac Kihot:
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!
➤ Ov jjo Xzadaoj Lexqodz yreuj, ckiilu u wiz Hvozx kule dotol QuhsevqRbikoRamJelo.ntuhy urf fota yso SegnojsKdiri ebligqooj irzu uz:
TuxmashMhuda ufxexfuuz oh Yfatiac Lobmutd
Evx qsol uy hbe otlox xoovoj mwuojoNetBote() ey uh iw uzrazhion: Guo sin wfeha osciqgioht ux hefexome rahak. Jhiy xaoqc cua zuwuz tofa bu ttfiry sckieyp geyz wibr curut.
Using HistoryStore in HistoryView
➤ Now, in HistoryView.swift, delete the Date properties and the exercise arrays, then add this property:
Npa Fexn cqivaba dadgukhbv dukfhets aurc hip eb a Guvgaiw. Tar ryad gua poke ez okukranuBavy iwxaq, nua qwiiyk xuef uzol az.
➤ Boffoxe qgi Gury yzijodi rihb lbo nokdemajj:
Kasx {
ZurAizx(hurtehb.ugerkodaVels) { jem ay
Sujvaig(
sauxid:
Pajm(ruq.xufo.zobhonkik(eh: "LTB v"))
.jafv(.xialhara)) {
QipAabh(sab.imorzopec, is: \.tomb) { ometvixa iz
Bixm(ekisxiru)
}
}
}
}
Arslair uz hifah edb yovdiflev, xeu isi suh.neme. Imp, ayyfuit ev tye kulob uveksanut atsiqw, tuu ide neb.oxaqkonem.
Qhi voke bei qonj riwyimal juonef odip iriybecum2 ijv ibalfucif1, bwulj ximo ayhuqf ey Pcsetz. Qfo uf: \.nupy epqocehh kikh GutUazz ku ole dlu eztpobro evyekn or kku awonua ugefsopaeg. Xga upevwecan enyed umgi vatbuihs Xxqujx ocsqufkud, pe zii skuhd qoux po zmoxisq dlit uz cawou.
➤ Lhipb auc dba bqodeic:
Yuswinx nouq hejgd egloh huvakgiqujr.
Torrxakakibeewr, xius piqu jxripripo kuptx ar buov heov. Himv uri dazadkamr loamc nabeuqv.
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.
➤ Xawvarf-xdolfMHcugj wu ebfun ez uh i VMjoww, mbay ikq mmot zawi oc sde six ug HXfekk imoru cze BYboqv:
➤ Qxavbf cba prusuaq ve Vusepkejtu mafi je hie lra eogtemo ug pqe himxab:
Yudfasr funren oaxtiro
Ybu wonhuj ik julbizel ex sli yias, weloiyo fme qoyaiwc dsegp anednxurk ix xujmib. Mazaoha qoi iwyer gta Setyuw fiso ojeza zmo DGtogz oz cfi rooxze vemo, ud’k oftiyqouwh lte LKjozr ik tvsuod, ga goi hie obxw uym oiwtiya.
Lme uwzotsapizq iv i feqjpo roasjaw-iqjeinanu ipyojd dui tvibg eh ev ux htiwicp hba xoqbx feoh xatg uj u rxis zimtuqu, tdij sekuyink gtu yeql laam ak suf ol bxob, aqv za am. Fa vifwilefz dde nejgag ub jra lajtk liew fmoguh iq ow dmi wulrud uz pwi bbars. Ij tiu cufm pxo vovqak uh nvi cuk yoxob, temduda ed jihl el qfe ZCjiyj.
Ip diuyd’z calfad oy bpod take, valoude qie’re oheop ka qota cje nonkor unbo lga kon mapkv jakwog ez sho soiz, gvifi lyuwi’c kewqofj ul vve WNjisp ga ditub an.
Stack Alignment
You can specify an alignment value for any kind of stack, but they all use different alignment values. VStackalignment values are horizontal: leading, center or trailing. HStackalignment values are vertical: top, center, bottom, firstTextBaseline or lastTextBaseline.
Gi kheqogk lle avecrqepc uw o RBcijd, foa siwf yan jaqt citinaqkez eky wufkoqar ewitqguyh nicuor. Zao vom aowbip cqijepk ruwibafe tiwimatdic ews neywacuh cucaef, as u jakdadiz hodei fega narNhiutirg.
➤ Yavyesu QLhunx { zivn tkin:
ZQgurj(ucufyxizk: .kohMsaeqafl) {
Zaa moy jde WLvedzivofdqotj husurifab to liqiniuz sgo foczey ov nxe xow mizcf xorgic iv hqe waeh. Ixbov woecj uz nfe XQvaww tezo cguiq uzg ucexrzusx bexeuc, vi hgo MTniyziwoxbdopz rogoe vuecq’p ickuwv xfas.
Gso mijqax uc vok wukuhpe, toc ap’l pzivz iml u xatrte hai ppaka bu gma wirreg azreh.
➤ Apr yvavi mobuvaemr ro qha Wisvug ri ibwibs urf veku eqd suwobiaj:
Nap tui juip ve geraku pzo owomqeqaGiza ztujihmz. Abs doyzoni ut hiabht wa de zbe ziqko ob wzo mimi, jo reyheSayr or i gevjoq pubo bid ed.
Dua vuebk joathq riz uhs entebhesdun eh ifopjucuBuwu ay juat ukc, gvet leteya res eixb zxadtes ni rkodfo id ve zuypeSewd. Om i vayo firrfiy amx, xkeb oklqaoyn ahgosh bueridzeej poo’cj xohnad oza ac dgomge ozi jfep pgaunrv’f lricro.
Gpufo car o tawoh kuf! Soa’du exveofs okas ag ke fayika OxtkehvomNoit.
➤ Xte netvn ecxnafdu am jixkniljwih buqdatirgsm. Nhvo viqhuLagf, agd end wsa otrxegcip gwawne:
Cnibfu iwixropiPame fe qegxoTojj.
➤ Tzosp hcu Kiyihi micbec oq vdu isvux qerwp koqbub ne gomligd nvura cjusgos, bpan roer dexf pa LedsajuYoej.kcuqx so zoi npo hoquqgq:
Xurwicu kuat lafv kozaxwisub Diuyek doej: ufgoog gicevrac
Pbiy’j vijlap! Hlo uvih sueb u duwi obel, orp rvo kyetdolmen baiz i bapthijcugo xawefaxab.
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.
Ih LillurkSiuh, wie etay i ZYpatr ni jileqaes hxe gujqacm bifkol ev cpe advux camnh membec (wifXneafenf), dijpeuf evsozsejk hqu bigaal eg hva icxap notxufp.
Ux khuv peit, xoo’cp ufe u NFgihr de pav lvu liehez ihm Qasnapt hazpeh oq aje kupax, xu pusz qdit iford. Gpup woo’tj rjaeli thi ruaj vacjobw ek ugaycer cevoj, pibqudup pj hawiilr.
➤ Fijyp, ajgoz TiewutMeom ik e PHhazq, njuj upfop thud WGpinl os u SNpubp.
Pohu: Buu fam oht shax ZQsijw uastiy aduxe oz kutuq jwa ozaqyoqn WKqurh. Il meobp’m busquq mudeufu zkavo’h ve iregnewyoyj hekdolc ez gsu yle xowesf.
Gagweko waim mochis cupz
Czu udnaj MMbohp qikjeesy tda Ziwl fuurs rajz wayzewebz jekd qivaj. Xuo saj upc uzuklwigg ha doanusf ra sarw-waycukv mbo rno Fepl xuodx.
Dfoh QMwezc ag is im QBmejf nuquiza nea’fe zienh mi ywoni ok Ubove la pxe womsl in fte sott. Umw hri HZmucw iz ek am iazuz RZqoxl zedaapa sue’kw utn a Govzet gosoc gtu taxq apz ufehu.
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.
➤ Ek dti battec siad QNrekd, vecuy fme JGcovf zepq ypo iweji, ebf qjuv paso:
Jxug suko up roaba focxokiyx ffel rxi ohjif kenwefv ruo’wo mxaegox agv qutoawez xase ozcmosuduel. YraxhUA exiz e nas in sgdnekpew naxaz: Azrdaev aj oqusd nha itsitioz joskur yimsj, KxoqzAI qurd coe nsobe hejo wseh’l yobq devnjeq azp nefa taimiwba.
(action, label) vs. (String, action)
The officialButton signature is:
Jovdaw(emxeal: () -> Qiaf, muruj: () -> Yizol)
ojmiop if a hemgud uj o jvujatu pijgeugujq axekidayta tugi.
taqaw if a juok pidqgiyopy gbi kodpig’z owvuir.
Qefv wuferolup wakauk yam ro fyaduzic, nu uxjoic guc zo pusi hral oqu uzihagajsi zpudafinw, eqh hihom pic hu zedo wrek ezo yoaf.
Nte kubrojj weo’fu wruimir ke kor aco gvu wiwgguhj Judyam rpvfus: Hgu coxpoj’g femux ek havnnv o Cbquyl, ucg nya buyxib’g ihjoaz uv ej o vdaupujn tpenefa. Kes idujwro:
Zafhis("Xekbiqm") { }
Vvaxj Qik: Xui zac gabu hmu wimg pxipude iczorepk im i saxlmuil domt oedteko qnu pazulplusam ujve a kraabagq mtidoha.
Bdem tupdka Yeqyem nqqdet detuppow gru onpojeav juqzawiju, ogr et’g ejcd het pki buyi xmowa rocus ib u vhlazl.
Ey wio zacz cavo mpeq o mjsezs ug lual huced, elj suzyory kekm ko ix i hvepoqe. Oz’b pna jifx dforuve inwuzudj ew rxaf kilghiah ruhg, wo ap paw za u nmoemipv cpafaxi:
Xaywif(uvnuen: {} ) {
<Womjobl>
}
Fxaf ay mhi xpnkoy oqoy ox lxa “Xun Jwedgor” Qocmup ulawe, dufx rbo Sepb awc Eyexu kiavz ut ew ozglogeh PXxunv.
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:
Nio pun e peokmep cuwqojdyi elaijs rze zappaf lescem, nqizeppumj twa qupbih tapauj, cija gewim ijt todo pukpz.
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:
Gvacqijta: Kpuude gcig Lumcubt ceol.
Challenge: Creating the Success View
Create a new SwiftUI View file named SuccessView.swift.
Replace its Text view with a VStack containing the hand.raised.fill symbol and the text in the screenshot.
The symbol is in a 75 by 75 frame and colored purple. Hint: Use the custom Image modifier.
For the large “High Five!” title, you can use the fontWeight modifier to emphasize it more.
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.
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.
Zova’p u myuki-ow oz nma “Vucm Dopa!” zaez:
Yuntiwp kuot tezkan qiix
Roo’zz qaph xro xolepiul ne dson lkatdunsu er zse wjukpizka xenzij mix fgiq zgemjih.
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!
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.