Present Modal View from Tab View in SwiftUI
Written by Team Kodeco
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.
Here’s how this code works:
-
@State private var isPresented = falseis a state variable that controls whether theModalViewis displayed. -
@State private var selectedTab: Int = 1keeps track of the currently selected tab. -
TabView(selection: $selectedTab)updatesselectedTabwhen the selected tab changes. -
Text("First Tab")andText("Second Tab")define the contents of the two tabs. -
.tag(1)and.tag(2)are used to assign unique identifiers to the tabs. This tag value is whatselectedTabis updated to when the corresponding tab is selected. -
.onChange(of: selectedTab) { _ in isPresented = true }setsisPresentedtotruewheneverselectedTabchanges, that is, when the user switches tabs. -
.sheet(isPresented: $isPresented) { ModalView(isPresented: self.$isPresented) }presents theModalViewwheneverisPresentedistrue.
For the ModalView:
-
@Binding var isPresented: Boolestablishes a two-way connection, or binding, to theisPresentedstate of the parentContentView. -
Button("Dismiss") { isPresented = false }setsisPresentedtofalsewhen tapped, dismissing theModalView.
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.