How do I generate a preview provider for a view which has a binding property?
struct AddContainer: View { @Binding var isShowingAddContainer: Bool var body: some View { Button(action: { self.isShowingAddContainer = false }) { Text("Pop") } } } struct AddContainer_Previews: PreviewProvider { static var previews: some View { // ERROR HERE <<<----- AddContainer(isShowingAddContainer: Binding<Bool>() } }
In Code above, How to pass a Binding<Bool>
property in an initialiser of a view?
The best solution here (to my opinion) is custom Bindings with a a wrapper View. That will give you two choices: Bind your (child) View with the parent View so that both parent and child can change the value. Don't bind child View with parent so that ONLY the child will save the value internally.
A binding in SwiftUI is a connection between a value and a view that displays and changes it. You can create your own bindings with the @Binding property wrapper, and pass bindings into views that require them.
PreviewProvider is a protocol used for generating previews that you can see on the right-hand side in Xcode.
There are two shortcuts that you should remember. Both of them will make your life easier during the development cycle of your SwiftUI views. Cmd + Option + Enter shows or hides previews. Cmd + Option + P runs the previews.
Just create a local static var, mark it as @State and pass it as a Binding $
struct AddContainer_Previews: PreviewProvider { @State static var isShowing = false static var previews: some View { AddContainer(isShowingAddContainer: $isShowing) } }
Other way
struct AddContainer_Previews: PreviewProvider { static var previews: some View { AddContainer(isShowingAddContainer: .constant(false)) } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With