swiftxcodeswiftuitabviewswiftui-tabview

Why does every item create an new TabView?


Every element in my SwiftUI code becomes its own TabView. It is not on one side how i want it. Every item is spread on another TabView.

I tried asking Chatgpt. He thought i gave every item its own tabView but I didnt. Then he thought i have to do it like this:

FirstView()
                .tabItem(Label("Text", systemImage: "doc.text"))

and not like this:

SecondView()
                .tabItem{Label("Gauge", systemImage: "gauge") }`

but that is not true so maybe someone can help. Thanks!

Output I get

The code:

import SwiftUI

struct MainTabView: View {
    var body: some View {
        TabView {
            
            FirstView()
                .tabItem(Label("Text", systemImage: "doc.text"))
            
            SecondView()
                .tabItem{Label("Gauge", systemImage: "gauge") }
        }
    }
}

struct FirstView: View {
    var body: some View {
        Text("Seite 1")
        
        Text("Zeile 1")
    }
}

struct SecondView: View {
    var body: some View {
        Text("Gauge")
        
        Gauge(value: 50, in: 0...100) { Text("Messung") }
    }
}

#Preview {
    MainTabView()
}

Solution

  • Just putting two views directly in the body of another View struct doesn't magically group them into one tab. After all, there are times when this behaviour is desirable - when you have a lot of tabs and you want to organise them into one View struct.

    The views in FirstView and SecondView need to be in some container in order for them to be in the same tab - think about how you want them to be laid out. For example, you can use a VStack if you want them to be on top of each other.

    struct FirstView: View {
        var body: some View {
            VStack {
                Text("Seite 1")
            
                Text("Zeile 1")
            }
        }
    }
    
    struct SecondView: View {
        var body: some View {
            VStack {
                Text("Gauge")
            
                Gauge(value: 50, in: 0...100) { Text("Messung") }
            }
        }
    }