SwiftUI Notes, Part 1: Data Flow

2019/8/21

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.

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")
		}
	}
}

Some videos and articles I found particularly helpful are:

So Technical It’s in English
文章列表