Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Hide a Tab View in SwiftUI
Written by Team Kodeco

Sometimes you may want to temporarily hide a tab view based on certain conditions or user interactions.

Here’s an example of how to do so:

struct ContentView: View {
  @State private var isTabViewHidden = false

  var body: some View {
    VStack {
      Button(action: {
        isTabViewHidden.toggle()
      }) {
        Text(isTabViewHidden ? "Show Tab View" : "Hide Tab View")
      }
      .padding()

      if !isTabViewHidden {
        TabView {
          Text("First View")
            .tabItem {
              Image(systemName: "1.circle")
              Text("First")
            }

          Text("Second View")
            .tabItem {
              Image(systemName: "2.circle")
              Text("Second")
            }
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
      }
    }
  }
}

Your preview should look like this:

You can use a Button and a state variable to hide a tab view in SwiftUI.
You can use a Button and a state variable to hide a tab view in SwiftUI.

In this example, you have a button that toggles the isTabViewHidden state variable when tapped. The TabView is conditionally rendered based on the value of the isTabViewHidden variable using an if statement. If the variable is false, the tab view is displayed; otherwise, it is hidden.

Using this approach, you can easily show or hide a tab view depending on your app’s needs.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.