Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding<Double> in SwiftUI preview

(macOS 10.15 beta and Xcode 11 beta 5)

A SwiftUI tutorial I was working through (https://www.raywenderlich.com/3715234-swiftui-getting-started#toc-anchor-005) included the following View:

struct ColorSliderView: View {

    @Binding var value: Double
    let textColor: Color

    var body: some View {
        HStack {
            Text("0").foregroundColor(textColor)
            Slider(value: $value, in: 0.0...1.0)
            Text("255").foregroundColor(textColor)
        }.padding()
    }
}

The view was declared in the same file as another View and could be previewed as a component of that View.

As used in the tutorial it works but I later extracted the View to its own file and added the following preview:

#if DEBUG
struct ColorSliderView_Previews: PreviewProvider {
    static var previews: some View {
        return ColorSliderView(value: 0.5, textColor: .red)
    }
}
#endif

This throws the error "Cannot convert value of type 'Double' to expected argument type 'Binding<< Double >>'".

Question: How do I declare a Binding<< Double >> with a value of 0.5 for use in the preview?

(Also: How do I include angle brackets in the question properly (without doubling them up)?

like image 428
Vince O'Sullivan Avatar asked Aug 10 '19 09:08

Vince O'Sullivan


1 Answers

value is expecting a binding. You can work around this by using .constant(0.5)

#if DEBUG
struct ColorSliderView_Previews: PreviewProvider {
    static var previews: some View {
       ColorSliderView(value: .constant(0.5), textColor: .red)
    }
}
#endif

But this is only intended to be used for testing.

like image 136
Marc T. Avatar answered Sep 28 '22 04:09

Marc T.