Say you have the following view:
import SwiftUI
struct BindingViewExample_1 : View {
@State var value = false
private var text: String {
"Toggle is " + (value ? "'on'" : "'off'")
}
var body: some View {
HStack {
Toggle(isOn: $value) {
Text(text)
}
}
.padding([.leading, .trailing], 80)
}
}
#if DEBUG
struct BindingViewExample_1_Previews : PreviewProvider {
static var previews: some View {
BindingViewExample_1(value: true)
}
}
#endif
This previews fine and you can interact with the control in the preview and see the changes immediately.
But what if it took a *binding* as input? Consider this alternate version of the same view:
import SwiftUI
struct BindingViewExample_2 : View {
@Binding var value: Bool
private var text: String {
"Toggle is " + (value ? "'on'" : "'off'")
}
var body: some View {
HStack {
Toggle(isOn: $value) {
Text(text)
}
}
.padding([.leading, .trailing], 80)
}
}
#if DEBUG
struct BindingViewExample_2_Previews : PreviewProvider {
@State static var value = false
static var previews: some View {
BindingViewExample_2(value: $value)
}
}
#endif
The only differences are in line 5 for the View itself, and in the preview code for both views. This compiles without errors but the preview no longer works. XCode just refuses to even create a preview.
If you keep the View as is but change the preview code to this, instead,
#if DEBUG
struct BindingViewExample_2_Previews : PreviewProvider {
static var previews: some View {
BindingViewExample_2(value: .constant(true))
}
}
#endif
Xcode now builds and displays a preview but interacting with it doesn't update the view. That's not surprising, given the `.constant(true)` binding, but that's the only way I managed to make the preview display when the View takes a binding and that's not very useful (since I can't interact with it).
So... what's the right way to write preview code for a View that takes bindings as inputs?