SwiftUI. How To pass Binding variable to PreviewProvider

Artem Mihelson
1 min readMar 29, 2022

Hi, this is a short How-To to give you an example on how to pass Binding<> variable to PreviewProvider.

Let’s assume you have a SwiftUI view with the Binding variable, that looks something like this:

struct ExampleView: View {
@Binding var isPlaying: Bool
var body: some View {
Button(action: {
self.isPlaying.toggle()
}) {
Image(systemName: isPlaying ? "pause.circle" : "play.circle")
}
}
}

In order to pass a Binding variable to ExampleView’s constructor in PreviewProvider you need to do the following:

struct ExampleView_Previews: PreviewProvider {
static var previews: some View {
ExampleView(isPlaying: .constant(true))
}
}

JFY, you can wrap anything, depending of what type of Binding variable you have. For example:

struct ExampleView: View {
@Binding var status: String = "pause"
var body: some View {
Button(action: {
self.status = "play"
}) {
Image(systemName: "\\(status).circle")
}
}
}

and PreviewProvider:

struct ExampleView_Previews: PreviewProvider {
static var previews: some View {
ExampleView(isPlaying: .constant("pause"))
}
}

That’s it. Happy coding!

--

--

Artem Mihelson

Founder of Pills.Kit, Proximodoro and WidgetLingo apps