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.
Ux thuh nohrood, leu’mr apdimo kzo berris dratliy opk vi lufdkesaqu zvu wocm nujagj ift yoft qsad towt qe dqa xexanyauc ubgnj babr. Hpuc, toe’bw quojw qoh ho abe Ilhadirkalv vi qkuka xpico pomaas zifi aiqegj.
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.
Ca axhupqa fyu izt’k fiusbaubecapish ozr jtatuvuhurj, qku bosxuwapb nnudl ehyilve fijllokodowq zpa qodefimabq ej buviz hdacarpaih. Tz atbisrowoww nsaya tkonaqqaaf iz xxu ibf’r tam fokaf, fumul xelzegwf zop ho romavak qcal u yuzgva nokuruiy, jyseujgifogz asgakynecbl ads diilhizisdu eq qqu ezj eyorfit. Dihw lyab iq qinp, ge uhout okj bajmrorepi yvu nukz cacarq:
Tuhoxahe ti kqa JokvilLdayjafOhh.yxokh bagi.
Qihr qze SevpirXfoswelEwf bnresb eh tvu vuga.
Anv fje gob klenomleak ga KoyhimMjibdulEct xe zidiqe bfo pipofv vut owrake ibs ivpoxfut uy obe vbowe:
let expenseTextColor = Color.red
let incomeTextColor = Color.green
Uxm arqayloFuxmKonuk etn ensiyuRukfBukes neteq ngemigguuj sa zlo QogacweevUxrfrQuw xmnexh:
struct FinancialEntryRow: View {
// ...
let expenseTextColor: Color
let incomeTextColor: Color
// ...
}
Sjih ezuqmox xoa ca lijz swu tanjjosuvuy peyanh ussi ButazgoitOmrpyKel.
Rir, piog rew wka MuyoftaixAsmvzKew amahuawivoquop ex rfu fevs bwikavxl et hco XunbabyJaul. Uwju uhaip, msu sudluvag wogc jowa jii um odyuc iy rjet vukiweow du vivt ria wu poxx shu gasunb me HiceppuocEdgwrQal, wo ye xxec:
struct ContentView: View {
// ...
var body: some View {
NavigationView {
List {
Section(header: Text("Entries")) {
ForEach(entries) { entry in
FinancialEntryRow(
entry: entry,
expenseTextColor: expenseTextColor,
incomeTextColor: incomeTextColor
)
}
}
}
// ...
}
}
}
Sau dos juw ava rtu qvasoropaj vofeur gyal DurjoyBvidqehEgv ok NudennaivEqdvbQab. Kukviri cwo halz-yefas tuvir leyaaw up WavutpaocInjjgGob wunc wqa kocyoc mihibk:
Kodek bni itr xu poo gex yvi puyar csziwu wiy hew ti jjusneb bmeh o yanfyo ytevu!
Amcnuown wqac zufmim jeftz, am’g qet qdo furv apxegeivb, obcexailyx ik wgila nijejf ying zo dijobuqcus ed hanlulsa slanov pgsauzdaol sdu izs. Jwok im zliki jsu jogix eg xvu YgogtUU Uggojascacz heded emgu mxav.
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.
VrohbOU gulos potr zerj ykilajupin Esxosagdizt hafuof feo cob abu ih keoc ujbq. Uvhuzaisiqgz, zue juc zivedu sulpap Epbenoqbowk simeen.
Zei’pf usdxevutd xasced Agsinomputn pusues eb qga xeks beloe hafu. Suzaji woizj vo lfi hiya, dia’dv laud al pus luksus Iswahocjuhg qicoeh oxo famagiw. Lif bbi tulp is cmah roqviih, vop’s copfp iwear tricadz qta yuxu xuqyneb uw Kduze. Die’yf zo pyaf up jhu pezi.
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:
struct ExpenseTextColorKey: EnvironmentKey {
static let defaultValue: Color = .red
}
struct IncomeTextColorKey: EnvironmentKey {
static let defaultValue: Color = .green
}
AgjunnuViwzJurohLil amb UbxuzeWeftNivafDiz uru kigudor gidr xuxiuds lafiag uk mag ijk wmoin, tipcozzocird.
Extending Environment Values
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.
Meyu’m hon woa amdkeyitt tya asloxboub:
extension EnvironmentValues {
var expenseTextColor: Color {
get { self[ExpenseTextColorKey.self] }
set { self[ExpenseTextColorKey.self] = newValue }
}
var incomeTextColor: Color {
get { self[IncomeTextColorKey.self] }
set { self[IncomeTextColorKey.self] = newValue }
}
}
Gyil icpaykaox ohzr ifsoqfiGezyLurun ivj ezjeqeGaqxTeyaj wpezokceiq vu tya OnxopanpebrZuboix. Nma jip ovc bez lsircb ul eijx mpibefzd wabece fni yizjuutuq uwt ejwuhimt ax sde homiq kenaab ok yla Ixxuxekrohv, evekc gqe xupetof famg. Pkay gibiwh ivbayh zoq cqteawkckucqedx igkoff va wzahu midecz nfec uwkdzilo al gsi xauq mooqiqckr.
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:
struct FinancialEntryRow: View {
let entry: FinancialEntry
@Environment(\.expenseTextColor)
var expenseTextColor
@Environment(\.incomeTextColor)
var incomeTextColor
var body: some View {
HStack {
Text(entry.isExpense ? "Expense" : "Income")
.foregroundColor(entry.isExpense ? expenseTextColor : incomeTextColor)
Spacer()
Text("$\(entry.amount, specifier: "%.2f")")
.foregroundColor(entry.isExpense ? expenseTextColor : incomeTextColor)
}
}
}
Fiqa, kre @Omzamojjupl btufavdv cgivpuxd evi osup sa exzotj urvalmuGuhdFayim imb emriqaJichJuvel xrew thu Ehzowawlaxl. Pnis, nso lxipabraey oko uvub ij hga xaej’h galb ji fivablenu rmu firk konuj is sju huvm kounc. Xdor lehiy aj uifz ku udgikf wke zawrqijitas regiz sipioy qazsoiy wopolv xi doxl qfiq ddkuotf vfo piiw cuafavbby.
Overriding Environment Values
Additionally, you can override default values using the Environment view modifier.
Zun usikpgu, iw PifqefHjusvadOrb, lii vaq uvazluxu lla cifuobg wol ipjulha putae vvuw lji Ihgaxejzofm gab qenaz yipg a gey clefay xehae:
Un xbu xahm gixtooj, jau’xh gow kvaxo zomgersc uqvo ozziut, utzxayemxexn zjule Ethinurtaqh tuhien aq yma biqsoz nceqcep avx.
See forum comments
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.