SwiftUI Notes, Part 1: Data Flow

2019/8/21 12:00 AM

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 Views 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 Views.

  • Use @State to declare a source of truth; it is available within the current View.

  • Use @Binding to link to @State variables in another View. 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 around Views.

  • Use @Environment @EnvironmentObject to allow Views to read data directly from the environment, instead of having to have the object passed around Views.

Some videos and articles I found particularly helpful are:

So Technical It’s in English
文章列表 归档