How do you preview a view containing a binding to its parent view's state?

百般思念 提交于 2021-01-27 13:10:31

问题


I present this view as a sheet from its parent view

struct NamesView: View {
    @Binding var match: Match

    var body: some View {
        ...
    }
}

Since the match source of truth is in the parent view presenting this NamesView sheet, when the view is constructed I pass in a $match binding and data flows as intended.

However, when constructing this view in a preview provider

struct NamesView_Previews: PreviewProvider {
    static var previews: some View {
        NamesView()
    }
}

the compiler says that NamesView() expects a match argument of type Binding<Match> (Match being the parent view presenting this view as a sheet). I'm not sure what would be a good way to proceed from here or if this is a limitation of SwiftUI.


回答1:


If you want only constant preview, then it can be

struct NamesView_Previews: PreviewProvider {
        static var previews: some View {
            NamesView(match: .constant(Match()))
        }
    }

if you want it in live, the it can be

struct NamesView_Previews: PreviewProvider {
    struct BindingTestHolder: View {
        @State private var testedMatch = Match()
        var body: some View {
            NamesView(match: $testedMatch)
        }
    }

    static var previews: some View {
        BindingTestHolder()
    }
}



回答2:


Try this:

struct NamesView_Previews: PreviewProvider {
        static var previews: some View {
            NamesView(match:.constant(Match()))
        }
    }


来源:https://stackoverflow.com/questions/60632339/how-do-you-preview-a-view-containing-a-binding-to-its-parent-views-state

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!