SwiftUI strange tabbar behaviour with groups

69 views Asked by At

I noticed a wired behaviour of the TabBar view and I'm curious if anybody else has made a similar experience or can add some knowledge.

Please consider the folowing simplified setup:

struct ContentView: View {
    var body: some View {
        TabView {
            DetailView()
                .tabItem {
                    Image(systemName: "star")
                    Text("Star")
                }
        }
    }
}

struct DetailView: View {
    var body: some View {
        Group{
            Text("Text A")
            Text("Text B")
        }
    }
}

Instead of one tabitem for the DetailView this creates two tabbar items and each represents one of the Text views. This can be fixed replacing the Group with a VStack or HStack instead.

But consider the following scenario now, where the inner views are displayed depending on some conditions.

struct DetailView: View {
    @State private let condition1 = false
    @State private let condition2 = false

    var body: some View {
        Group{
          if condition1 {
            Text("Text A")
          }

          if condition2 {
            Text("Text B")
          }
        }.onAppear {
          self.condition1 = self.checkAuthorization()
          self.condition2 = !self.condition1
        }
    }

    func checkAuthorization() -> Bool {
      // ...
      return false
    }
}

Now the tabbar stays empty. I assume this is because the group is empty initially (with both conditions set to false). But I thought that's what a Group is actually for? What is the best practice in that case?

0

There are 0 answers