30

有了新的@Binding委托和预览,我发现总是必须创建一个@State static var来创建必要的绑定有点尴尬:

struct TestView: View {
    @Binding var someProperty: Double
    var body: some View {
        //...
    }
}

#if DEBUG
struct TestView_Previews : PreviewProvider {
    @State static var someProperty = 0.7
    static var previews: some View {
        TestView(someProperty: $someProperty)
    }
}
#endif

有没有更简单的方法来创建绑定,代理一个简单的值来测试和预览?

4

1 回答 1

46

您可以.constant(VALUE)在预览中使用,无需创建@State.

/// A value and a means to mutate it.
@propertyWrapper public struct Binding<Value> {

    /// Creates a binding with an immutable `value`.
    public static func constant(_ value: Value) -> Binding<Value>
}

例如

TestView(someProperty: .constant(5.0))
于 2019-06-07T12:56:35.410 回答