如何为预览创建简单的绑定

时间:2019-06-06 21:26:42

标签: swiftui

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

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

是否有一种更简单的方法来创建绑定,该绑定代理用于测试和预览的简单值?

1 个答案:

答案 0 :(得分:2)

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

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

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

例如

TestView(someProperty: .constant(5.0))