Search code examples
swiftswiftuitabview

Swift: If statement in TabView


Here is my TabView code:

struct HomeScreen: View {

private enum Tab: Hashable {
    case schedule
    case messaging
    case home
    case resources
    case settings
}

@State private var selectedTab: Tab = .home

var body: some View {
    TabView(selection: $selectedTab) {
                Schedule()
                    .tag(Tab.schedule)
                    .tabItem {
                        Label("Schedule", systemImage: "calendar")
                    }

                Messaging()
                    .tag(Tab.messaging)
                    .tabItem {
                        Label("Messaging", systemImage: "bubble.left")
                    }
                Dashboard()
                    .tag(Tab.home)
                    .tabItem {
                        Label("Dashboard", systemImage: "note")
            }
                Resources()
                    .tag(Tab.resources)
                    .tabItem {
                        Label("Resources", systemImage: "folder")
                    }
                Settings()
                    .tag(Tab.settings)
                    .tabItem {
                        Label("Settings", systemImage: "gear")
            }
    }
    .id(selectedTab)

     }
 }

My main question is, how can I import something like this when you click the Settings Tab:

 var array = ["email1", "email2"]
 if array.contains(userEmail) {
      AdminSettings()
 } else {
      Settings()
 }

The final goal of this is the detect if the user is a "administrator" based off the array, and take them to a different page from the normal settings.


Solution

  • You can use Group for this, like

        Resources()
            .tag(Tab.resources)
            .tabItem {
                Label("Resources", systemImage: "folder")
            }
        Group {
              var array = ["email1", "email2"]
              if array.contains(userEmail) {
                AdminSettings()
              } else {
                Settings()
              }
            }
            .tag(Tab.settings)
            .tabItem {
                Label("Settings", systemImage: "gear")
        }