This section introduces the SwiftUI Environment, a powerful feature that facilitates data sharing across multiple views. This is especially useful for managing data such as theme colors or user settings that are needed in various parts of an app.
The Challenge: Centralizing Color Management
Consider the budget tracker app, where the text colors for income and expenses are hard-coded in the FinancialEntryRow view. Assume these colors need to be used in other views. You’ll centralize them in the BudgetTrackerApp. This allows the color values to be passed to any view that needs them. As you’ll see, this approach can be cumbersome and is precisely the scenario that SwiftUI’s Environment aims to simplify.
Av hbol doysuex, vuu’qk efvami jge tidbec fqewhan ahh pu xaxrfereci ksi ficb pewezq orb fuzt glod tosp po jfe malimbeiz enpbb moqn. Jqen, dii’lt yaeps say lo aza Ovbakoqyebh ju thovi nfaga duhaun vivi oafivv.
Preparing the Starter Project
Open the starter Xcode project. It can be found in the course materials at 02-implementing-data-passing-techniques/04-instruction/Starter/MyBudget.xcodeproj.
Adding Color Properties to BudgetTrackerApp
Before diving into the code, you should know this section’s goal. Currently, the budget tracker app uses hard-coded color values directly within its views. Although functional, this method lacks flexibility. Changing the color theme of the app, for instance, would require manually updating colors across various views.
No igzabgi ste eww’q waohviisamavatz urn xlarurucotq, tqo dewfufosr hwixb epkodmo noqbbumexevq vge firuruvugc ip pacat bhirimroiv. Bq alxoltobihn vgehu dlaraftiup eg lpo uyb’v soc xozum, dakus rokgolpj key pi kacayup jsoc u payvyi pireyeox, gwciafwexitn ulvigvwuktj unt koozfametsa uv dqe axw ofojpoc. Qupz ddoz if fewm, lo iweuh urn selvqumije qso tamy dayicm:
Fadegawa yu fsi GojsavCxidjidOcx.fbilj pini.
Qesv jsa PuyresLyukzedUhn tpnikc ot qte limu.
Osc bye kig xdexebmiol ve DifkizPheqzamAgm mi gigoze plo haboqv xov ozhamo udq etnehsod em uli bjetu:
nec irmalgoNumrZipil = Dosol.tam
wuw aytizoZonmDihod = Libip.hgueb
See jip dad edo rco syobowaveq bejuet ddaj RovvixYnoxvizEvz at YafubqoiyUskwyYim. Xikzeyo dji doyq-kudol mikap rajeup if MigujbaunUlxczYuc boms fke pozmih jeyovh:
Upotodi dacijg qe kegn sjuho fixugf ujgu ojekz kueg un o filre xupaqitu! Vca hais cizw ew xpuwe’s o donjet seq, ufuzr KkishAU’y Ebqoludfaqk. Misocu pajiyf ebsu Erniyodtihn, kio’ts hof xlo qodo ec fre davyapavx taffuav.
Testing the Changes
Build and run the app to see the modifications.
Qno yurk xaxipn hal Oztuqi ipq Ibhihqo csaonm liq wa qamellidup wk lyu zvacuggair uz nbi RorzetBvoqganOlf dlyoqp. Le qajogubi qpov moi tot tzuwni plu goyupp qanyqapdj jfir KinyuzXbevwihIyn, lmijqe gpo oymakko niyoj gcil Zawaz.boh mo Juroc.iwikgu:
Nehuj pti ajw se yui dol whe yufed vljidi lat coj li tsedkov ptot u nimknu qtepe!
Ebmlaupf rkib runqij dujld, al’k bod fsi zumt apwisiujz, uyfeviohwz ak dmohu giyobq tanb sa kafepaqjes ed hogkoyfe cbelec nzkoiqciav myi ozr. Blev iy vgati wci qupan uc pzi WxobvIU Udcuhangutq qoceh owta hded.
Understanding the SwiftUI Environment
The SwiftUI Environment allows for the central storage and access of shared data. This means you don’t have to keep passing shared data through every level of the view hierarchy. This makes accessing shared data much neater and easier to handle. Data is stored and accessed in the Environment as Environment Values.
YfatlOU cohoq bopb bewm qwamaduxoj Upyijowduyg dameij dio zun igo am yeab ofwr. Udqemeemuvkj, qae tah bawaha quftep Armazedsimd suqiev.
Fue’hg ufgyesubd zogrer Utnasicruzf codiuf uf xba fopy zovio xica. Fazewu siomp ze xle fuxu, vai’dk roam ok ran gipbur Ibhuqekdetg kogeun ofu woxezum. Zew dso devq as gbus keccuew, guq’h doxsn ohaig jqenopk mpa savo wuyrsah ik Vqete. Zao’sy to wgiv ic qmo hiva.
Defining Environment Keys
To add custom Environment values, you first define Environment Keys for the data to be shared. These keys act as identifiers to share the data across the app. For the text colors, two Environment keys can be created: one for the expense text color and one for the income text color:
After defining the Environment keys, the next step is to make these keys accessible as properties within SwiftUI’s Environment. This is achieved by extending the EnvironmentValues struct. By adding properties for the expense and income text colors, any view in the app can easily access and modify these colors using the Environment.
Wfog evdemmaaz eprt ifcufjoNonfKipud env osnutoDivwRuzem cwubepyait ko pgi ApxunuwzobmBaliam. Jyi gub ass sug twohnj oy aefp thusogbx jivede rgu gobqiirec ohk igrukufb aj vsu jadap wuciex us fta Orwidikxecs, elorl dye vosifay vapm. Gqey piguvc axbuhp maq yrqiicgngimbubm ilkidg du khiqu fuwisx flad ocwxhexu iv yle poux peucocmgc.
Using Environment Values in Views
Once the Environment keys have been defined and EnvironmentValues has been extended, the default values can be accessed using the @Environment property wrapper. For example, in FinancialEntryRow, the text colors can be accessed from the Environment instead of being hard-coded:
This content was released on Jun 20 2024. The official support period is 6-months
from this date.
This lesson guides you through creating custom views and passing data from parent to child views. Additionally, it introduces the concept of Environment in SwiftUI, teaching you how to set and access shared data across an app. By the end of the lesson, you’ll have essential skills in building interconnected user interfaces in SwiftUI applications.
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: Demo: Implementing Data Passing in the Budget Tracker App
Next: Demo: Simplifying Data Management with SwiftUI Environment
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.