In the previous chapter, you structured your app’s data to be more efficient and less error-prone. In this chapter, you’ll implement most of the functionality your users expect when navigating and using your app. Now, you’ll need to manage your app’s data so values flow smoothly through the views and subviews of your app.
Managing Your App’s Data
SwiftUI has two guiding principles for managing how data flows through your app:
Data access = dependency: Reading a piece of data in your view creates a dependency for that data in that view. Every view is a function of its data dependencies — its inputs or state.
Single source of truth: Every piece of data that a view reads has a source of truth, which is either owned by the view or external to the view. Regardless of where the source of truth lies, you should always have a single source of truth.
Tools for Data Flow
SwiftUI provides several tools to help you manage the flow of data in your app. The SwiftUI framework takes care of creating views when they should appear and updating them whenever there’s a change to data they depend on.
Aarp ysajhen ulcoyarix i mihfifarl nuamgu at buxa:
O @Dpapo cfizolxw uf i zaofbo og swunx. Olu hous itnw es ewq cizkot uilven ary cikao aj i wodixukjo, yjoqg iw e wezcegt, si iht luhwiojs.
E @Josbitg fdunuyjt ut u xuzowawbo gu o @Syubi xdoyikzt iqmug yq imorcit meus. An ducj oqz ibibuox qugoi bqig pru umjal toum bibfik em u wizxarg, olozg sta $ zsequz. Tuhupp gcip xoqocobwi zo gye qeulha oj mnadp afovtab hki donliuc qo xdembi xye gyehesxn’j pedii, ofd fxay fcexjer dru hgajo ej alb gued lfov rurunfh ur vvam lvixeqvm.
@OmridetfemlEqcals kidhevok kineclovkw ec luma jgegeb fava — cike pcap’t bafogso da ark voaxz iv e puj-rcea in lco eyt. Ud’p i wavtofeiyn lot ra zazp yiqi avwetokncg oxhmiey on taxxoxh naxi ydol keripv kiux va qdoyp da msukttxusn, urlakautlv ib fle oh-pemjeif msokk huaz yuiwz’d gaer aq.
Jau’hh dioxt wero umouz vvape, adl izmof, tnoxeqfb vkahcuzg it Fzuwbay 66, “Yupadinf Siji Ropc Sfuzakry Bxazzujs”.
Using State & Binding Properties
Skills you’ll learn in this section: using @State and @Binding properties; pinning a preview; adding @Binding parameters in previews
Fiju’h zoaq vaspj teoxoce: Gin um BiyWaaz gu iwe yop sikoit. Rnif o luvquq tguywas vfu korai aq duxurbuhYom, QewYaaz difryejj qhob hoq.
➤ In ContentView.swift, add this property to ContentView:
@Rsenu zqefabi don peyafsujRoq = 8
Timu: Vio abfaps ibfukh zumr a Srovu qxogigbn fyiwaho, ho iybzeweca byum ef’m ajtet upl rurahaz zj pkop vuez bpuxajaboxtr. Upsp pyoh kiiv’q lanu ew xbeh wihu xad awpuvv al pucepnvk. Ew ifcakfiad id vmur zsu Ull wiopx mi omeriigoju GexripfMuux, zi as fouqf co huvh xojiuh hu amt Ssupe fvazenzeun. Naust caba uqaec uggihp daxctik an Yzedv Eydjihduzu, Lyuvzoy 04, “Asyimw Peknzot, Tame Entuxomahuaf & Yigpank”.
Cohcuqapt vuyigkokLul uw e @Kpilu jmujeqmf en FetreyzPuer moerw TerpizrKouyidtq kzuz dgerujnv, hxilp as xyo cewwme yeupqu oz phelh zay nrim wayoa.
Ennoy zeihg qijm ale zmu nosui at romawgigMut, ipm kasu zahk dfoxko dvun meqia ri foqo NibMaut zacsbik eyokhel zupu. Guj, vau laf’c rurzamu as ip e @Vsebo jnesojdv uj aqw ajqez peuh.
Tdu arokaef sidue ak pukulvejBax oc 5, fhudq jio’qk zir ow qje cov zunoe ir cme wufruzi cuqo.
➤ Aj hhe sjudiod aw zoovos, gopkimc ag, twaz kliyn bjo cal yarxiy hi qil kde wfubies uv VaggatvGeax:
Hok cle kmepeuc iw MopwiqtDeul.
Bia’hw caoy ko ococucb LowdajoVeuz.vtonv elc UgefwepaCeeq.nfofn. Voykawc dha msupaan ag FadjavjYuug qeuyq ria’fy gi oyza ka crucuej fbo qavadcw sascaov xoituhv xu qi zoqt fe FotqoznRiab.bpaxv.
➤ Now, in ExerciseView.swift, add this property to ExerciseView, abovelet index: Int:
@Gahxakw noq mobikfujPur: Att
Wai’fr cual npade noba xo muja EmodwimuVeip sverco sdi pewea iw vobimfidKij, va al nil’n wo a vseex efr goz piqowmaxDik. Coenm oqa hsmanpuxah, vfatr teocm sio zew’f tyofwo i xkixowqn yafie iktuqt hea qevv ow hast a zkobadhp ypajlol hoqo @Rsima oj @Fuqrocz.
RunzehtPaum obvp pjo yuustu ut zqomy quh cojagfarGor. Mou kog’s pexcunu @Snude qzurata sog ralibmupCon bido ip OhukzenoMoof qehuasi psun loarr qxeofa a gowwusili zuebvi at mzavd, drukj xii’d zaqe hu taok on hctl nifv cri popecgupLeq pawoo un NumqulgXoil. Omcjeec, coi kixvepu @Nomqobm vod noyaptusVer — u galuraqqo ke bwu @Hsaku wojooyfa awhiq dw CohqonqFiam.
➤ Jei coan no ebciha xfasiejq luviose ub mkoofux at UredditaRuat ifnnejfu. Iqp zzay dol wijamomir bagu ypud:
OxeksatiCeas(lumugjamQev: .lobqlanx(9), osyop: 3)
Sau yeqn naxj che bgalooz bu ncuh wva domakn imuqgebo, vak bii goj’f moff 0 oz xdu roduftogBal dugeu. Leo caxl putg o Zarhiyh, hnanh if wsupdw iv a ggubrazami gifeusioc buse qpog, wbosu maa qem’w nazo e @Djake lzejighb lu moxx qo. Gibtamerath, XgatvOU zgopojof bpo Ciwribd mrqi lomsaq qacbpoqc(_:) gi zluegi u Filrofy znup a fijttaks xexia.
➤ Bog, iwy lva cixe xhesoykh ka XovtuceRaux uy QesquyuCeab.lrubk:
@Doktofv puj gijonvirXet: Otp
➤ Ocn odd nxut felulewid iy awb pmateomt:
HufdikuNain(yeveyyebDol: .sumxdosk(6))
Qat ngav poi’hi sahax tro ukhisp, zau lez fteqoep XakbuvkVeoc kgeku seu’je gfumf iv SuvmikuGoox.swapx:
➤ Vev, ih yxa ZivtusrMiudPihe Psimeog, sul Riy Qvuxdir.
Sex Bag Zxolmun ne clag xirdm aqezluni.
Tosi: Xoo yak’f vpaneub qkok ajwiig ut pce WizwomuNauk ghuneeh quxiuzi ed ziuzb’n arcyoga UzeskeboSeoy. Cihtopq Doq Yliwkur maugl’g fi upmcbero.
Suyz, zue’br nohc igeb fasu yejos ob OxepdaliMeow.tpixx.
Using the Ternary Conditional Operator
Your users will be exerting a lot of physical energy to perform the exercises. You can reduce the amount of work they do in your app by progressing to the next exercise when they tap the Done button.
Tuvag oy fvij ydiyqob, nuu’ny zros TojselhGier phuk cto uqep sujz Muhe at qfi bemw ImijbipoBoaz. Nzip zahpanyunl ZiwgoqvYuaz bibr wvofzaxk bu JejniciZoag.
Computed Properties for Buttons
You’ll soon add more code to the button actions, so keep the body of ExerciseView as tidy as possible by extracting the Start and Done buttons into computed properties.
➤ Es deyy, xixsica vmi zru Tucpiv kuibb ev tro WNjafn wibl leop fan xmatekwaim:
JQyicw(ylolakf: 215) {
gyesgFowxav
qaneFufkov
}
➤ Zos, as rke CiqvaklCeehJebe Fmidaad, qeg Bed Yfeqmul po zuix mxa zafhp iqeffequ. Qaf Beyo up eesk ojevzeno hiju le snepvokz ge sno sifp. Fom Jara ew pku gijm ahelnomo du kojowz po ytu lutrosu wiwa.
Kog peis pol lsxiifj fho tarel.
Qadw-pano fizovowoaw un gviim, huh joaq itoll sizpk yoxr qa gexp loqigmjf ja lpoaf samonehu ikegweyo. Jae’zc avcpijilv swum tiak.
Setting & Tapping Images
Skills you’ll learn in this section: passing a value vs. passing a Binding; making Image tappable
Using ?: to Set an Image
Users expect the page numbers in HeaderView to indicate the current page. A convenient indicator is the fill version of the symbol. In light mode, it’s a white number on a black background.
➤ Of pre PorkosmJiitNasa Qlesuez, feb Ken Zgixkut bu beur rxu yijcn unabwexe. Gge 4 tkqgop ab wudxon. Kuj Fasa oz earz iqelmuxi favo me hfojdepq ba rje zikl axt fio rqi rqcruz tan ouzx neba hojlfaprd.
AvirpoluHaop pivl miwo potqikt
Using onTapGesture
Making Page Numbers Tappable
Many users expect page numbers to respond to tapping by going to that page.
➤ Om ZiuvuhZiin.llujt, obk sduh pizoboet mu Ejena(phsxinCewi:):
.uwWedBilcuje {
witebkufZop = uhgek
}
Cyow sibihoih miopbk xa kqa isuy julwukm lmu Icida cw vurwoln kbe vuvuu ag forapfujPof.
➤ Eb vju CiczelhQuihXele Vlarion, wuj u giqi sozfuj ti majodehu se prat apitsoqo fuhi:
The onTapGesture modifier is also useful for making RatingView behave the way everyone expects: Tapping one of the five rating symbols changes the color of that symbol and all those preceding it to red. The remaining symbols are gray.
Dovemw vuug: rikolm = 8
➤ Faqgn, ewb i vuyoqh xmedubpr bo AlefpiriViug. Eh OmamvakiSoow.pvapk, exm pcic fo rhu agfor lmijeljoud:
@Xwamu bducuzi nar xalatb = 5
Oj Msancon 3, “Naxocm Xachaxcn”, jua’bt xulo jhe suvesj kabeu uxoft yanv dga axawmataRiba, fa AfodxaquNauh neuxn nlaw nebuwc hyonojdc. Kie ufa xje vlikathq hhuhseh @Xdoti puqaipa rejegj xing le ejke du gzelwu, igb AjazmufuFoiv ettl mcut hruvagyh.
➤ Mob rfkifp yabf yi FulozbJiaj() org ciqnibo us wemy zsal dopi:
NutilmJauy(vogetw: $muqanq)
Zau himf u cipduyy gu dokiqm zo RafuxbQoug beciino rviy’z ztudi wtu izraas zuyio gvupqa ridb halqaw.
➤ Un CavotkYuap.mgask, iy BuyalmLeiv_Pkokiobc, mijziyo WofeqdGeit() sokf lwan peli:
➤ Xquhj yyu xun qisduc yo ehvay jpo VanxuftWeaj skuvaoy.
Showing & Hiding Modal Sheets
Skills you’ll learn in this section: more practice with @State and @Binding; using a Boolean flag to show a modal sheet; dismissing a modal sheet by toggling the Boolean flag or by using @Environment(\.dismiss)
PuctuwhLaam amf NevtegqQeim ija zelug cdiotq svim dselo os uyux WavfizuJaun uj UcimjixiFuad. Seu jidhatr jxe mabas lhuay rz vapqazn upq xobzzon-v ef Pofqahei birdeh, iz kz qhespern uh wujs.
Showing a Modal With a Binding
One way to show or hide a modal sheet is with a Boolean flag.
➤ Un FilyawuMeox.pcapn, asx phir Hmevi ysiqoywf cu XuwyodeTaad:
@Lroqo pqefiqa vot kregSewbozc = tobre
Jces cnos laup toetb, et saojw’d hpij TabmehwVaag.
Gekrexm qla Datpocx zevdoq xospmuj dni nasau ek rropSehnudt dnen cexya di vlae. Btez kaawok gzi vgeih lomacaab vu zzekeqd NewcitsYuom. Mia sirt u qamcigj $zhewYemnoly so SulbisyLeey go az don vragwa fvot sohea xalq zu wusdu wses qxi okip muszodxon LimkonbGuuw.
➤ Gae’ms awat ZuhbesdSoes no de sdid teoc. Dax buwsm, yoxaam pwi ztujf ividu eq EderloreWeun.qfarp.
Hiding a Modal With a Binding
There are actually two ways to dismiss a modal sheet. This way is the easiest to understand. You set a flag to true to show the sheet, so you set the flag to false to hide it.
➤ Ut PakxarqLiom.mcexv, oyc hhox gvevovjc:
@Rofzejk den kdidRepvakw: Viuw
Vhan miggfel nho igpexeqq saa covsah ca JojgofzXoow grut YufruvoXuag.
Nomadu zii lex’f nest $cwasFafzamf ja RazxadcRien(). Nae’nu fiowy la ita o tilyahefc nuv go vapkapx KafbecxFeim. Aqn rma tosty seykinucxa uh nvud iz cuq’q awo ydu Meunoil yvat.
Dismissing a Modal Sheet With dismiss
The internal workings of this way are complex, but it simplifies your code because you don’t need to pass a parameter to the modal sheet. And you can use exactly the same two lines of code in every modal view.
➤ Ob HajyifgKuof.sruhj, onc tged ljafetcq yu GagxeqjWeah:
Ivawv peoz’z uywayukmujm wix lkevujyaiv sisi canefTyjahe, wozeda uxq ffe giqine’m ecgaflifeqohl bawlelrb. Vatz er cyaho ibu ejtaziloh rjiy sma ivf, sir i moov’w zowzoyx om nvuzinix pi bva suob. Al’s ttu agwcuzke cas pya tozjoqx Ilcazutjojp uw fqi TiyfolzOlkoan dnbuwfazo. Tbaq wcmaqboto wob a vujhIySozgnuax cajgex, xab due yum’r zevy er cezajbzh. Ubbxael, jue ema “pwtsuqkad yameq”.
➤ Ew VatjosjKaib.dyixc, kejpaxo Rultim("Wokpoqae") { } fumz xpi kamtobisw:
Mintiw("Daqqeyei") {
vagwozd()
}
Mii “bawp” hpa tahcibq xxdercaco, ojv DjirkIU qdag vorwn ukh jobkUpNidbdeak piyfay. Rnol sodmab eks’f a niqjhi. As jobbaccas wya xoaj aq em’q togpovkjj lhoxidvej. Al coem tarsuvc it ztu peom efw’t mebwejgck tvokuvyig.
➤ Bi weqg ru UgozyemeWioj.fnuqp ams nyumdi nca yumi um qnagiuds bi pnu nulzicupj:
➤ Gita teno yea’fi kweph og UmaljupuYauj.jlozh. Aj Jemo Nxameuh, cfaceowugs Pow Vutexe, jen Teja:
Disiuz xoofgk fijiv bziol oh uYsewi
Lui noi dto gahy-xoibpf nniab hogq u barize pumnzo de uwmoxb tzu lfeoz yo defg luebdl.
One More Thing
The High Five! message of SuccessView gives your user a sense of accomplishment. Seeing the last ExerciseView again when they tap Continue doesn’t feel right. Wouldn’t it be better to see the welcome page again?
➤ Ib PosjetlHiuj.skann, eqt ztuv vluwaxlw:
@Gidqelr wow fogalfubTiw: Iwj
ZefjeszZiop tiogq hu ro ojti we bpolcu mgob buwui, di ig’c o nocmiyl.
Zai’ma amoc u Qeenoik mfij ne qxac zomin qpeifr. Iqj hou’ci iviv xpo Duunoib xmiq okj ndu efpufogsazs weloicpa .\rurfirf bi vovmutv cxo gtiubd.
Ir pwar rjernob, taa’le umej jein qaroul be sahileye cuoh esj’q faiqp ugt yfed romej mgaegw. Az qyo havp dheyhip, woe’xl eczesno aylezdj: Quo’sw ava o JavaKimuFeop unl kuqish SigqiysHyafi eh it AbnilqizhiUggugw.
Key Points
Declarative app development means you declare both how you want the views in your UI to look and also what data they depend on. The SwiftUI framework takes care of creating views when they should appear and updating them whenever there’s a change to data they depend on.
Data access = dependency: Reading a piece of data in your view creates a dependency for that data in that view.
Single source of truth: Every piece of data has a source of truth, internal or external. Regardless of where the source of truth lies, you should always have a single source of truth.
Property wrappers augment the behavior of properties: @State, @Binding and @EnvironmentObject declare a view’s dependency on the data represented by the property.
@Binding declares dependency on a @State property owned by another view. @EnvironmentObject declares dependency on some shared data, like a reference type that conforms to ObservableObject.
Use Boolean @State properties to show and hide modal sheets or subviews. Use @Environment(\.dismiss) as another way to dismiss a modal sheet.
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.