Last active
August 11, 2024 00:21
-
-
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
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
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
Demo:
2022-09-02-SwiftUI-Stateful-previews-Binding.mp4