-
-
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.
This file contains hidden or 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