Oleg Titov
Oleg Titov

Reputation: 61

Xcode 12.3 puts any new piece of content in a new preview

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.

Upvotes: 1

Views: 264

Answers (2)

Asperi
Asperi

Reputation: 257493

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")
      }
    }
}

Upvotes: 2

Boris Gutic
Boris Gutic

Reputation: 1

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

Upvotes: 0

Related Questions