Skip to content

Instantly share code, notes, and snippets.

@alexobenauer
Last active June 11, 2019 00:49
Show Gist options
  • Save alexobenauer/dee289a7fc793f92cb459ab006ea4f86 to your computer and use it in GitHub Desktop.
Save alexobenauer/dee289a7fc793f92cb459ab006ea4f86 to your computer and use it in GitHub Desktop.
How bindings work in SwiftUI views
//
// SwiftUI-BindingExample.swift
// SwiftUI-DataFlowExamples
//
// Part of the series beginning at:
// https://medium.com/@alexobenauer/demystifying-data-flow-through-swiftui-697017aba7e0
//
import SwiftUI
struct PlayButton : View {
@Binding var isPlaying: Bool
// This is a binding. It is a reference to a read-write value
// passed in from a parent view. Writing to the value causes
// SwiftUI to update all of the views which use it.
var body: some View {
Button(action: {
self.isPlaying.toggle()
}) {
Text(isPlaying ? "Pause" : "Play")
}
}
}
struct ExampleParentView : View {
@State private var isPlaying: Bool = false
var body: some View {
VStack {
PlayButton(isPlaying: $isPlaying)
// To pass a binding of state, you use the $ prefix,
// which gives you the binding rather than the value.
if isPlaying {
Text("Currently playing")
}
// This is automatically updated by SwiftUI when
// PlayButton changes the isPlaying value.
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment