80 - Present Modal View from Tab View in SwiftUI

In SwiftUI, it’s easy to present a modal view from a tab view. You can use the built-in sheet modifier to display a modal view when a user taps a tab item.

Here’s an example of how you can present a modal view from a tab view:

struct ContentView: View {
  @State private var isPresented = false
  @State private var selectedTab: Int = 1

  var body: some View {
    TabView(selection: $selectedTab) {
      Text("First Tab")
        .tabItem {
          Image(systemName: "1.circle")
          Text("Tab 1")
        }
        .tag(1)

      Text("Second Tab")
        .tabItem {
          Image(systemName: "2.circle")
          Text("Tab 2")
        }
        .tag(2)
    }
    .onChange(of: selectedTab) { _ in
      isPresented = true
    }
    .sheet(isPresented: $isPresented) {
      ModalView(isPresented: self.$isPresented)
    }
  }
}

struct ModalView: View {
  @Binding var isPresented: Bool

  var body: some View {
    Text("This is a modal view.")
      .padding()
    Button("Dismiss") {
      isPresented = false
    }
  }
}

Your preview should look as follows. To see the ModalView, run the example in the simulator and tap either tab.

It's possible, although not best design practice, to create a tab view that presents a modal sheet.

Here’s how this code works:

For the ModalView:

This code allows the ModalView to be displayed whenever a tab is selected, and to be dismissed when the button in the ModalView is tapped.

And that’s it! By using the sheet modifier and a little bit of state management, you can easily present a modal view from a tab view in SwiftUI.