SwiftUI 画布预览显示一个视图的多个视图

7 xcode ios swift swiftui xcode-previews

我的 SwiftUI 预览将一个视图显示为 3 个不同的预览屏幕,它应该是一个具有组合视图的屏幕......

我究竟做错了什么?

谢谢你!

请参阅 3 个独立预览视图的附加图像。在此输入图像描述

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()
    }
}
Run Code Online (Sandbox Code Playgroud)

jn_*_*pdx 6

SwiftUI 预览将显示视图树根部每个节点的预览。当它位于预览本身内部时,这一点会更加清晰,例如:

struct SignupSelfie_Previews: PreviewProvider {
    static var previews: some View {
        SignupSelfie()
        SignupSelfie2()
        SignupSelfie3()
    }
}
Run Code Online (Sandbox Code Playgroud)

在上面,很清楚为什么会有 3 个预览。

在您的示例中,正如评论者提到的那样,它发生在您的系统中SignupSelfie,因为您的根节点有 3 个节点:

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

我的猜测是你的缩进可能使它看起来像SpacerText位于VStack- 一个好技巧是选择你的代码并使用Ctrl-iXcode 自动格式化 - 它将修复这样的缩进问题并揭示问题。

在这种情况下,您可能只想将所有内容放入VStack. 在其他情况下,很高兴知道您也可以避免此问题,并将多个节点包装在Group {}