-
-
Save peterfriese/16c139f63335e6fe32ffcb7ba2529970 to your computer and use it in GitHub Desktop.
A container that makes implementing stateful previews in SwiftUI easier
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
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 | |
} | |
} |
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
// 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