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

rec*_*ter 4 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

Run Code Online (Sandbox Code Playgroud)

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

Mat*_*ini 9

您可以.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>
}
Run Code Online (Sandbox Code Playgroud)

例如

TestView(someProperty: .constant(5.0))
Run Code Online (Sandbox Code Playgroud)

  • 给出的答案是正确的;我不想暗示其他情况。但我想正在开发的视图首先具有“@Binding”的原因是因为该视图会改变该数据,并且在实时预览中测试它会很好。对于给定的答案这是不可能的,因为 `.constant()` 的结果是一个不可变的绑定。让它改变的方法在 WWDC 2020 题为“为 SwiftUI 预览构建应用程序”的演讲 (https://developer.apple.com/videos/play/wwdc2020/10149/) 中给出,从 16:43 开始。 (7认同)