SwiftUI canvas preview displaying multiple views for one view

3.6k Views Asked by At

My SwiftUI preview is showing one view as 3 different preview screens and it should be one screen with the combined views...

What am I doing wrong?

Thank you!

See images attached of 3 separate preview views.enter image description here

struct SignupSelfie: View {
    @ObservedObject var signupImagesViewModel = SignupNavigationViewModel()
    @State private var isValid = false
        
    var body: some View {
      
        VStack {
           Button("capture") { /* action code here */ }
              .background(
                  NavigationLink("", destination: SignupIdView(), isActive: $isValid)
                )
            }.navigationBarBackButtonHidden(true)
            Spacer()
            Text("capture selfie")
        }
}


struct SignupSelfie_Previews: PreviewProvider {
    static var previews: some View {
        SignupSelfie()
    }
}
1

There are 1 best solutions below

1
On BEST ANSWER

SwiftUI previews will display a preview for each node at the root of the view tree. This is more clear when it's inside the preview itself, like:

struct SignupSelfie_Previews: PreviewProvider {
    static var previews: some View {
        SignupSelfie()
        SignupSelfie2()
        SignupSelfie3()
    }
}

In the above, it's clear why there would be 3 previews.

In your example, as a commenter alluded to, it's happening in your SignupSelfie because you have 3 nodes at the root:

  1. VStack
  2. Spacer()
  3. Text("capture selfie")

My guess is the indentation you have may have made it look like the Spacer and Text were inside the VStack -- a good trick is to select your code and use Ctrl-i to have Xcode auto-format -- it'll fix indentation issues like this and reveal the issue.

In this case, you'll probably just want to put everything inside the VStack. In other cases, it's good to know that you can also avoid this issue and turn multiple nodes into one by wrapping them in Group {}