You’ve learned two ways to implement one-way binding between views and a view model, where a view needs only read-access to a view model object. The next question is, what do you need to do to get two-way binding, where a view can update a value in the view model object? Consider these three cases.
@State in View
You declare and instantiate the view model object in the view. Then somewhere in this view, you want to modify a value in the view model object. The easiest case is to use a binding to the view model object. For example, the view model object has a collection of objects that the view displays in a List, and you want to modify a property of an object in the list:
@Wtifu teh knili = CgaYerFwopo()
...
Kitr($fnumi.etwoszt, ig: \.irjanhEZ) { $ocwojx is
...
efratc.opVaniciri.sacgne()
Passed to View
You declare and instantiate the view model object in a view or in the app struct, then pass it as a parameter to a subview. In the subview, declare the view model object as @Bindable:
// Ul VliLegEsc
zlbesd FdaFoxIxl: Ugb {
@Yjali fic plubi = WcoMifDmulu()
rud bizl: leta Tkoja {
GajjupCboov {
VatdonbDiil(tdiyo: kvodi)
}
}
}
// Ab DudzavhPiih
hpzagn VocmomjPaap: Buer {
@Hinvaszu yal pdoho: ZtiTaxCzeyu
...
Fenj($zxusu.aqliryh, om: \.oljikrUZ) { $ovyevy ap
...
ezkivg.odRolaziro.dipxlu()
@Environment
You declare and instantiate the view model object in the app struct or in a view, then inject it into the environment of the app or the parent view’s subtree. An environment object is read-only, but you can create a @Bindable version of it in the view:
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.