Previewing view with Binding variable

Hello,

I'm having trouble previewing a view that has a binding variable. When it's in the below state, I get the error "Edit placeholder in source file":

    static var previews: some View {
        Navigation(viewState: Binding<String>)
    }
}

When I put a string as a placeholder, I get the error: Cannot convert value of type 'String' to expected argument type 'Binding<String>'

    static var previews: some View {
        Navigation(viewState: "sign-in")
    }
}

The code for the supporting view with the binding variable is below:


struct Navigation: View {
    @Binding var viewState: String
    
    var body: some View {
        ZStack {
            HStack {
                Spacer()
                Button(action: { toggleView(view: "savings")}) {
                    Text("Savings")
                }
                Spacer()
                Button(action: { toggleView(view: "settings")}) {
                    Text("Settings")
                }
                Spacer()
            }
        }
        .position(x: UIScreen.main.bounds.width / 2, y: UIScreen.main.bounds.height / 2)
        .frame(width: UIScreen.main.bounds.width, height: 100)
    }
    
    func toggleView(view: String) {
        viewState = view
    }
}

Any help would be greatly appreciated.

Hi @marcofusco111 ,

There's a few options here. One is to use a constant value like this:

  static var previews: some View {
        Navigation(viewState: .constant("sign-in"))
    }
}

The other is to create a preview container that creates state variables and passes them in as bindings to your preview. Then in your preview, you would just preview the "preview container" which has its own source of truth.

struct NavigationPreviewContainer: View {
    @State var viewState: String = "example"
    var body: some View {
        Navigation(viewState: viewState)
    }
}


struct NavigationPreview: PreviewProvider {
    static var previews: some View {
        NavigationPreviewContainer()
    }
}
Previewing view with Binding variable
 
 
Q