Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI preview provider with binding variables

Tags:

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?

like image 938
Sagar Kothari Turvo Avatar asked Feb 07 '20 00:02

Sagar Kothari Turvo


People also ask

How do I pass a binding variable in SwiftUI?

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.

How do I use binding in SwiftUI?

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.

What is PreviewProvider SwiftUI?

PreviewProvider is a protocol used for generating previews that you can see on the right-hand side in Xcode.

How do I run preview in SwiftUI?

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.


2 Answers

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)   } } 
like image 87
nine stones Avatar answered Sep 27 '22 23:09

nine stones


Other way

    struct AddContainer_Previews: PreviewProvider {       static var previews: some View {         AddContainer(isShowingAddContainer: .constant(false))       }     } 
like image 25
Ernist Isabekov Avatar answered Sep 28 '22 00:09

Ernist Isabekov