通过实时预览(SwiftUI)执行动作/使用手势

时间:2020-03-15 19:50:24

标签: swiftui action gesture preview

我有CustomToggle,我想通过Live Preview对其进行测试。问题在于,通过Live Preview轻触切换没有任何作用,但是在运行Simulator时效果很好。

struct CustomToggle: View {
    @Binding var isOn: Bool

    // ... displaying CustomToggle view
    // ... and toggling isON onTapGesture

}
struct CustomToggle_Previews: PreviewProvider {
    @State static var isOn = true
    static var previews: some View {
        CustomToggle(isOn: $isOn)
    }
}

1 个答案:

答案 0 :(得分:0)

您可以为此定义一个结构:

struct StatefulPreviewWrapper<Value, Content: View>: View {
    @State var value: Value
    var content: (Binding<Value>) -> Content

    var body: some View {
        content($value)
    }

    init(_ value: Value, content: @escaping (Binding<Value>) -> Content) {
        self._value = State(wrappedValue: value)
        self.content = content
    }
}

然后像这样在预览中使用它:


struct CustomToggle_Previews: PreviewProvider {
    static var previews: some View {
        StatefulPreviewWrapper(false) { CustomToggle(isOn: $0) }
    }
}