Last active
June 11, 2019 00:49
-
-
Save alexobenauer/dee289a7fc793f92cb459ab006ea4f86 to your computer and use it in GitHub Desktop.
How bindings work in SwiftUI views
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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