Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
684 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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()
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...