Skip to content

Instantly share code, notes, and snippets.

@ole
Last active August 11, 2024 00:21
Show Gist options
  • Save ole/4c43c92fe425d662186afd04dd800b4f to your computer and use it in GitHub Desktop.
Save ole/4c43c92fe425d662186afd04dd800b4f to your computer and use it in GitHub Desktop.
A wrapper view that provides a mutable Binding to its content closure. Useful in Xcode Previews for interactive previews of views that take a Binding. https://twitter.com/olebegemann/status/1565707085849010176
import SwiftUI
/// A wrapper view that provides a mutable Binding to its content closure.
///
/// Useful in Xcode Previews for interactive previews of views that take a Binding.
struct Stateful<Value, Content: View>: View {
var content: (Binding<Value>) -> Content
@State private var state: Value
init(initialState: Value, @ViewBuilder content: @escaping (Binding<Value>) -> Content) {
self._state = State(initialValue: initialState)
self.content = content
}
var body: some View {
content($state)
}
}
struct Stateful_Previews: PreviewProvider {
static var previews: some View {
VStack {
Text("Interactive Previews for Bindings!")
.font(.headline)
Stateful(initialState: true) { $state in
Toggle("Toggle", isOn: $state)
}
Stateful(initialState: 0.25) { $state in
HStack {
Text("\(state, format: .percent.precision(.fractionLength(0)))")
.padding(.trailing, 20)
Slider(value: $state, in: 0...1) {
Text("Percentage")
}
}
.font(.body.monospacedDigit())
}
}
.padding()
.previewLayout(.fixed(width: 300, height: 300))
}
}
@ole
Copy link
Author

ole commented Sep 2, 2022

Demo:

2022-09-02-SwiftUI-Stateful-previews-Binding.mp4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment