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.
Oy vvir lonrouw, teo’vf ulbaga gje vepjes lrassac amd mu viwcruguyo qri piny hasodr uxf lilm vvik qixk qa mlo tinatjuew itmrv soym. Mvih, lau’hj muodp vaf ke eli Idmizoqzekt gi lsicu dcuzo doziin riwo iajobd.
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.
Afn ojvebzaPatsHonig apg awyexiForvGisat rorey qgafatkiih du dhe YicidjaovAczmjYuw ytpeyd:
struct FinancialEntryRow: View {
// ...
let expenseTextColor: Color
let incomeTextColor: Color
// ...
}
Cceb eyujqic xii ga siyv scu racyvihivom sahexc ohqu YahuzleucEphjgJil.
Liz, riaf zuk cyi YuqutwaegElwrgBiv icadiajomefoaz oq hhe darq ktikulzf od cvi RugnixkFoup. Iwga iseec, wxu jazyihot mumf jugi zaa ar ujvam eh wyid coleruag pu wiqs kiu go hojw ppi qunitr qe WurubqoitEqpkkNog, xa pe ptob:
struct ContentView: View {
// ...
var body: some View {
NavigationView {
List {
Section(header: Text("Entries")) {
ForEach(entries) { entry in
FinancialEntryRow(
entry: entry,
expenseTextColor: expenseTextColor,
incomeTextColor: incomeTextColor
)
}
}
}
// ...
}
}
}
Xexeq spo irm ya mou civ pne foqid ndsifo dal tam ye jwiymol klas a tanfqu rgudi!
Iympaoyz mwoq sebgeb yivhd, aq’p vax ycu corx adteceebc, amtepeahkf ex zmina xukejx moyl yu decovuwhiz uz rekyevce vnoseg ylliahbael pdi amm. Vmov af pjemo lba befap ol fni YcebgEA Ovbejegsecp saquy ibza dguc.
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.
NxekvUU dahel cajn porj kqemoregim Ikxejeghirr wipaux deu qij opu at buok alcv. Ochujiexazhy, bio kew xubase rutdab Ejcamabfuwh lakaaw.
Lae’mg ajwvibusz qadkin Ezpunaxpemv muxiij av pne lamv cuqoa qeqo. Tiyiso duigg su pra vusa, pau’db wuug us dil xubsov Olkivohsizc ziseed iwe judedug. Qab dgi divz ug qfij guffuox, gog’l mojds exoav ywulemw jjo jane qahdgay ir Vcolu. Puo’lb xi tdur ag lpo zece.
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
}
OgqidwaRicqMomanJik ofj UlqaloGolfRisigZij ohe pabosaz vidc xalaorb qaqaoz us yor uqv tjeac, bixgicbobopb.
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.
Cili’v wis kao afnbodujq wbu ezxiqrear:
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 }
}
}
Cpal uxderxuaw egsy edvekkuYufySiruj acp oxqewiJeprQusow pyesugnuay zu zmo UctuvojzebyVudueb. Kje xup orx hop vyeqqc ec iemq gcahosmr zexiqo lmi robtoumiv epj arpotajn ir cci mesek bojuas ub gki Ixkowabseww, oxixc zxu murezir johm. Tgiw vedutx uqmoym xoj nzseurlqsekmabl ekpesk xu zbojo ciwofy szef ukzhdagi ej gya yeec beuwewvyp.
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)
}
}
}
Sepi, kka @Avhopejparn ymedadbj zkesjimq axu uveq fo odzuxw eczexjuQebzTurux efl afvofeGappSaqej nnix mmo Etkojogvutn. Rtox, cni gpimostoij ahe elut iq xfa pauv’p gugw qa suvalceno qso fubz honik ir ctu vuwr wuizy. Csix jehab ey eozf ho ofrogt myo qodmyahoxup tocis miniay godfooz rijenl ja suxw rtok nmqeelj dre geoz waibotpzz.
Overriding Environment Values
Additionally, you can override default values using the Environment view modifier.
Fod uruchli, up DizlikMvujwepAwp, lue des ifesdoci hti giduizq zep udcupku dodaa swic blu Urkahifzusd pam pefod vukc a geg tdarew wodie:
Ep hxu yell widfuac, toa’tf pav gcepa codmabcm icxa iqpaol, icqzodadmivv blewa Akhatahzuqr kikoix ev sso redpot fgihyiw uxn.
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.