SwiftUI如何在View需要初始化器中的@Binding时实例化PreviewProvider


10

使用SwiftUI(Xcode 11.1),我已经通过2路绑定(使用@Binding)设置了一些视图。双向更新效果很好。

但是,如何从PreviewProvider实例化视图?

例如:

struct AddProjectView: View {

    @Binding public var showModal: Bool

    var body: some View {

        return VStack {
            Text("Add Project View")
            Button("Dismiss") {
                self.showModal = false
            }
        }
    }
}

我无法执行此操作,因为“ true”不是绑定:

struct AddProjectView_Previews: PreviewProvider {
    static var previews: some View {
        AddProjectView(showModal: true)
    }
}

我不能这样做,因为“ 本地属性尚不支持属性包装器 ”:

struct AddProjectView_Previews: PreviewProvider {
    static var previews: some View {
        @Binding var show = true
        return AddProjectView(showModal: $show)
    }
}

我们如何做到这一点?

谢谢!!

Answers:


15

.constant 正是为了这个目的:

///创建一个不可变的绑定value

struct AddProjectView: View {
    @Binding public var showModal: Bool
    var body: some View {
        return VStack {
            Text("Add Project View")
            Button("Dismiss") {
                self.showModal = false
            }
        }
    }
}

struct AddProjectView_Previews: PreviewProvider {
    static var previews: some View {
        AddProjectView(showModal: .constant(true))
    }
}

完善!-太棒了!
drewster '19

5

您必须在预览中将其声明为@State。

struct AddProjectView_Previews: PreviewProvider {

     @State static var showModal: Bool = false

     static var previews: some View {
         AddProjectView(showModal: $showModal)
     }
}

还请记住,它在静态函数中使用时必须是静态的。


1
XCode 11.3中的行为实际上与using相同.constant(false),即,如果您使用实时预览,则不能更改该值。
Fabian Streitel

4

如果只需要一个常数,请使用.constant(VALUE)

struct YourView_Previews: PreviewProvider {

    static var previews: some View {
        YourView(yourBindingVar: .constant(true))
    }

}

如果您需要一个可以在实时预览中更改的值,我喜欢使用此帮助程序类:

struct BindingProvider<StateT, Content: View>: View {

    @State private var state: StateT
    private var content: (_ binding: Binding<StateT>) -> Content

    init(_ initialState: StateT, @ViewBuilder content: @escaping (_ binding: Binding<StateT>) -> Content) {
        self.content = content
        self._state = State(initialValue: initialState)
    }

    var body: some View {
        self.content($state)
    }
}

像这样使用它:

struct YourView_Previews: PreviewProvider {

    static var previews: some View {
        BindingProvider(false) { binding in
            YourView(yourBindingVar: binding)
        }
    }

}

这使您可以测试更改实时预览中的绑定。


您不知道您的答案如何帮助我生成更好的代码。太感谢了。我仍在学习您编写的SWIFTUI和BindingProvider,这超出了我的有限知识。我有一种感觉,但不了解100%。不管怎么说,还是要谢谢你。
GrandSteph

乐意效劳!继续努力,继续学习:D
Fabian Streitel
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.