Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Create a Modal View in SwiftUI
Written by Team Kodeco

Modal views are an excellent way to display focused, temporary information or gather input from users without taking them out of their current context. They’re typically used for tasks that require completion, or dismissal, before a user can interact with the rest of the app.

Creating modal views in SwiftUI is straightforward thanks to the sheet view modifier. This modifier requires a binding to a Boolean value that determines whether the sheet is presented. When the bound value changes to true, SwiftUI presents the sheet.

Let’s illustrate this with an example. You will create a simple button that, when tapped, presents a modal view:

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

  var body: some View {
    Button("Show Modal") {
      showModal = true
    }
    .sheet(isPresented: $showModal) {
      Text("This is a modal view")
    }
  }
}

Tap the Show Modal button and your preview should look like:

A simple modal in SwiftUI.
A simple modal in SwiftUI.

In this example, you declare a @State property showModal to control the presentation of the modal view. You use $showModal to create a two-way binding to this state. This means that when the showModal value changes, SwiftUI gets notified to update the UI. When the Show Modal button is tapped, you set showModal to true, which triggers SwiftUI to present the sheet.

The content of the modal view is defined in the trailing closure of the sheet modifier. In this case, it’s a simple text view, but you can customize this to fit your needs.

And there you have it! You’ve just created a basic modal view in SwiftUI using the sheet modifier.

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.