skip to Main Content

Xcode preview screenshots

import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Hello")
        Text("World")
    }
}

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

The code above results in two preview windows: one with text "Hello", second window holds "World"

Every time I add something like Text() or whatever, it appears in the second preview window. Adding more elements automatically leads to new preview windows. THe code in the PreviewProvider remains the same, so it’s not duplicate previews, it just the separate previews for EACH element…

I tried to restart Xcode, change simulator devices, create new projects – nothing changes.

It started after I added duplicate preview in one project and then deleted it by removing appropriate lines in the PreviewProvider. After that all new projects or all new files in old projects show this strange behaviour.

2

Answers


  1. You have to put the two Text elements into a Container, like e.g. a VStack.

    Login or Signup to reply.
  2. The body by default is a @ViewBuilder in SwiftUI 2.0, so it just generate a group of views inline, thus having two Text element you got two previews. If you want just one Preview your body should have the one top view, like

    struct ContentView: View {
        var body: some View {
          HStack {
            Text("Hello")
            Text("World")
          }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search