Skip to content

Instantly share code, notes, and snippets.

@seanlilmateus
Forked from ole/Stateful.swift
Created September 2, 2022 15:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seanlilmateus/7c9657982fd0eb69a4ad908a1455be1a to your computer and use it in GitHub Desktop.
Save seanlilmateus/7c9657982fd0eb69a4ad908a1455be1a 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.
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))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment