StatefulPreview
is a simple struct wrapped in a PreviewProvider
extension that enables stateful previews for SwiftUI views.
Fields wrapped in @Binding
annotation, are not easy to preview as stateful value. It's possible to wrap a value using .constant
utilty but it will not allow to modify the value.
This example shows how to use StatefulPreview
with a simple value type.
struct CountView: View {
@Binding var count: Int
var body: some View {
HStack {
Text("The current count is: ")
+ Text("\(count)")
.bold()
Button { count += 1 } label: { Text("Add + 1") }
.padding(6)
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(12)
}
}
}
struct CountView_Previews: PreviewProvider {
static var previews: some View {
Stateful(value: 1) { count in
CountView(count: count)
}
}
}
MIT