Create a Full Screen Modal View in SwiftUI
Written by Team Kodeco
In SwiftUI, full-screen modal views can be created to utilize the entirety of the screen’s space, capturing more of the user’s attention than a regular modal. The following example demonstrates how to implement a full-screen modal view in SwiftUI.
Start by creating a simple modal view:
struct FullScreenModalView: View {
@Environment(\.dismiss) var dismiss
var body: some View {
VStack {
Text("This is a full-screen modal view")
Button("Dismiss") {
dismiss()
}
.foregroundColor(.orange)
.padding()
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(.blue)
.edgesIgnoringSafeArea(.all)
}
}
In the FullScreenModalView
above, you have a Text
view and a Button
. The Button
is designed to dismiss the modal view upon being tapped. The foregroundColor
, padding
and background
modifiers are used to style the button, and the edgesIgnoringSafeArea
modifier ensures that the modal view covers the entire screen, even beyond the safe area.
Next, create a main view to present the modal view:
struct ContentView: View {
@State private var isShowingModal = false
var body: some View {
Button("Show Modal") {
isShowingModal = true
}
.fullScreenCover(isPresented: $isShowingModal) {
FullScreenModalView()
}
}
}
Tap the Show Modal button and your preview should look like this:
In the ContentView
above, the fullScreenCover
view modifier is used to present the full-screen modal view when the button is tapped. The isShowingModal
variable is toggled to true
to trigger the presentation of the FullScreenModalView
.
And that’s it! You’ve successfully created and presented a full-screen modal view in SwiftUI. Remember to consider full-screen modals for navigation workflows or when you need to focus more of the user’s attention.