xcodeswiftuiswiftui-previewscontentview

In Xcode 14.3.1 using SwiftUI and preview, why doesn't the preview display both of my Views? (It shows them on separate previews)


My app is made up of two Views. When I run it on the emulator, it looks like the following (minus the red bar - I added that to the image to make explaining this a bit easier):

Main Screen made up of two views

All of the controls above the red line are in one View and the one control below the red line (OtherOne in green) are on another View.

When I run the app it looks like the one you see in that image.

However, when I do a preview I get two different View pages in XCode.

It looks like this:

content view 1 content view 2

I have to click each of the (ContentView) bubbles at the top so I can see each one separately.

Question

I'm wondering why the preview doesn't show them as merged -- the same way I see them in the actual app?

My Swift app looks like :

import SwiftUI

@main
struct FirstSwiftUIApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
            OtherView()
        }
    }
}

My ContentView file has two separate Views (ContentView & OtherView) in it and looks like the following:

import SwiftUI

// preview moved to the top so you can see it contains both Views
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
        OtherView()
    }  
}

struct ContentView: View {
    var body: some View {
        VStack {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundColor(.accentColor)
            Text("Hello, world!")
            Button(action:
                    {print("it worked")}){Text("simple")}
            Button(action:{
                if let url = URL(string:"https://newlibre.com/librestore"){
                UIApplication.shared.open(url)
            }
                
            }){
                Text("Load NewLibre")
            }.padding(5)
        }
        .padding()
    }
}

struct OtherView: View{
    var body : some View{
        VStack{
            Button(action:
                    {print("This is the other one!")})
            {
                Text("OtherOne")
                    .font(.title2)
                    .foregroundColor(.green)
                
            }
            
        }.padding()
    }
}


Solution

  • You have two previews because you currently have two items at the root of your previews:

    struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            ContentView() // <-- 1
            OtherView()   // <-- 2
        }  
    }
    

    In order to get them to display in one preview, you should have one root (in, for example, a VStack):

    struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            VStack {
               ContentView()
               OtherView()
            }
        }  
    }