Skip to content

Instantly share code, notes, and snippets.

@peterfriese
Last active March 17, 2024 08:20
Show Gist options
  • Save peterfriese/16c139f63335e6fe32ffcb7ba2529970 to your computer and use it in GitHub Desktop.
Save peterfriese/16c139f63335e6fe32ffcb7ba2529970 to your computer and use it in GitHub Desktop.
A container that makes implementing stateful previews in SwiftUI easier
struct StatefulPreviewContainer<Value, Content: View>: View {
@State var value: Value
var content: (Binding<Value>) -> Content
var body: some View {
content($value)
}
init(_ value: Value, content: @escaping (Binding<Value>) -> Content) {
self._value = State(wrappedValue: value)
self.content = content
}
}
// Here is how to use the stateful preview container
struct TodoRowView_Previews_withGenericWrapper: PreviewProvider {
static var previews: some View {
StatefulPreviewContainer(Todo.sampple) { binding in
TodoRowView(todo: binding)
}
}
}
// Everything below: views and data model used in the above code snippet
struct Todo: Identifiable {
var id = UUID().uuidString
var title: String
var completed: Bool
}
extension Todo {
static var samples = [
Todo(title: "Write sample code", completed: false),
Todo(title: "Draft article", completed: false),
Todo(title: "???", completed: false),
Todo(title: "PROFIT!!!", completed: false)
]
static var sampple = Self.samples[0]
}
struct TodoRowView: View {
@Binding var todo: Todo
var body: some View {
Toggle(isOn: $todo.completed) {
Text(todo.title)
.strikethrough(todo.completed)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment