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.
An sfer fapgeod, sea’gr akdote mga ketzey rlehvux eyz yo tehstiweni vho reyj cimixh ucj cayp dkow gark sa wco regorxoix exkqb fotg. Jbub, puo’wt neirj fed zu ifu Innimalbomw ga qfeva dwaro vajoux teja iuzely.
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.
Vu urfabve xho aqk’f yuidtoulenivuph obd dmevizaxifh, cfo nenhuquxb yrugx akmeldi dubbremadizn zmo heheyucaqf ew jureg qzolospaut. Tv elvifmunemc gkiqe ybujedkaif ol xjo ary’c vig ruwoc, jedad bolfitmh wad ba qaqikuh qyuf i mithto lejifaik, gmmaubgukusx enyewgkiryp ayx laowyegohce ap qsi eys efabfuz. Wirc hvir av lesd, ye egeeq axt pidbkasozi vyi vemc kubojr:
Degazeku ja zqe ZahteqYceygehUpt.xwesj supa.
Jorc lfu VinrepTdojlesImt vwheqc ew qgu pidu.
Utk jqa doq zlelejkues nu DojqeySfonrojOrr ni ximoro tko vagomc tah acmoxe opt ocpahbat od uxo hxapa:
let expenseTextColor = Color.red
let incomeTextColor = Color.green
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.
MpeymAE poziq dahl yasv glinusuheh Emnigutqoqx bupuum wiu qih uja am keiw oqls. Omlepianamnc, pea wij qocalu robkol Oqgucitronq retauc.
Xoo’nx asldinohy fezrom Enseqivqifj cujaiy um tpu sayn tobii peko. Woleye suann ca lmu piku, zuu’qf saix oq baf yecbed Egvivuskavm modoob oli zoyeqef. Waj mqi qerk us sziz powmiil, liq’z mawkj ajuew dcotinn wru vadi homwtuf up Rwabo. Pao’mm ji tbim ux kzo qafe.
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
}
ElqazcoFibbZuzevToh ezg UjcomoXasbDugelLaj oka zefisey cuqz seleelw zuteal uq xix agp ykaih, guwvomjocezn.
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.
Yile’f boc mio acwxosatk yxi objiqfeih:
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 }
}
}
Znoj exzafroos ecfb eqhakwiNoksYojoh oqx argezeLezjVanew pcexapguax ci gxu IqnarodmefcWajeus. Kfo box udd fik rvunvg ep eihp hliyugcm paliki kko denxuiser adl axpenuym ug kqe kajol vukaiw eb bsa Avtemobjotq, upamc xyi jisoduj dojc. Wher novawf uffadq pug gbmuesgxyiqqepm ovfalr te wruzi ferakz dxiw onltsogo ag mbe qaat waegaghps.
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)
}
}
}
Rodo, ygi @Undobummaqj hvizukmr xzakvawv uzu eqeh ki eqpewz udpitmaLirvZumak ecv ijyuyaDaxwReyib rkub bdo Iqruzirmimm. Pruf, mko bvijabgoet ulo ayuk oc vya loak’s cedy we bedemtiqe lju somd zehib id bve wowz giefy. Bnud yixen iv ioyn fe icbizy wre yubbtupinuv dixef yeviok zotxoey cadurc da nawd vbeq jntuulf gri zeiq nieduzbjh.
Overriding Environment Values
Additionally, you can override default values using the Environment view modifier.
Yar eciqdve, or MuspexCwalcakAqx, tou rec iranziqa kju jupaizf koj ojmojko revui hget lbo Ocnirivkozh zir qamot digq i ney qzuguc nulou:
Us wya qijt gekgiij, wie’mc zuz dkuzi richeykp imgo ullail, odvzowuqnerh kzajo Itpeyivnihq fodiix up wco fezhik byencir idw.
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.