It’s been a while since I started learning SwiftUI but the framework has only matured in the last month or so. A lot of things changed since the first developer’s beta in June — gone are NavigationButton
, PresentationButton
and a ton of UI elements has seen a change in implementation.
But as we near Apple’s September Xcode GM launch, now is a good time as any to learn about SwiftUI and see the framework with fresh eyes and entirely new mindset. With SwiftUI, everything is a View
— a Button
, a Toggle
, a TextField
— everything. View
is a function of @State
; variables declared as a @State
are managed by SwiftUI, and a change in value will cause subscribing View
s to update and render.
I’m still trying to wrap my head around how things work in the old UIKit framework, but I’ll start with passing data around SwiftUI View
s.
-
Use
@State
to declare a source of truth; it is available within the currentView
. -
Use
@Binding
to link to@State
variables in anotherView
. Doing this makes sure you have one source of truth, and you don’t need to worry about keeping them in sync.
struct ParentView: View {
@State var isGreen: Bool = true
var body: some View {
Rectangle().fill(isGreen ? Color.green : Color.primary)
ChildView(isGreen: $isGreen)
}
}
struct ChildView: View {
@Binding var isGreen: Bool
var body: some View {
Toggle(isOn: $isGreen) {
Text("Background")
}
}
}
-
Use
@ObservableObject
to define your own data model that is passed aroundView
s. -
Use
@Environment
@EnvironmentObject
to allowView
s to read data directly from the environment, instead of having to have the object passed aroundView
s.
Some videos and articles I found particularly helpful are:
- Data flow in SwiftUI - Apple’s WWDC video
- Making apps with Core Data - Apple’s WWDC video – There’s a specific section on how the new features in Core Data will enable List View in SwiftUI
- Majid’s example of how Property Wrappers work