SwiftUI canvas preview displaying multiple views for one view
Asked Answered
H

1

7

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()
    }
}
Honeyhoneybee answered 21/3, 2021 at 16:8 Comment(1)
That is happening because your Spacer() and Text("capture selfie") are outside of the VStack.Binnie
B
6

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 {}

Bergeman answered 21/3, 2021 at 16:51 Comment(1)
Thanks for the fix and explanation (altough, I'm personally at a loss as to why the entire var body.... isn't just viewed as a single node - isn't that it's point in a released app....?). In my instance Group also did the same thing and it had to be a ZStack.Meister

© 2022 - 2024 — McMap. All rights reserved.