Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Configure Modal View Height in SwiftUI
Written by Team Kodeco

Configuring the height of a modal in SwiftUI is easily accomplished using the presentationDetents modifier. This modifier allows you to set the available detents, or heights, for the enclosing sheet. If you provide more than one detent, the user can drag the sheet to resize it between the given heights. By default, sheets support the large detent.

The PresentationDetent struct represents a height where a sheet naturally rests. There are several predefined cases for common detents, including .medium and .large. You can also create your own custom detents by conforming to the CustomPresentationDetent protocol.

In the following example, a modal sheet is presented when a button is pressed. The sheet’s height can be adjusted by the user between the medium and large detents.

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

  var body: some View {
    Button("Show Modal") {
      showModal = true
    }
    .sheet(isPresented: $showModal) {
      Text("Hello, world!")
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(.blue.opacity(0.2))
        .presentationDetents([.medium, .large])
    }
  }
}

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

A modal view with configurable height in SwiftUI.
A modal view with configurable height in SwiftUI.

In the sheet(isPresented:content:) method, the presentationDetents(_:) modifier is added to the content view, specifying the available detents as [.medium, .large]. This enables the sheet to be resizable between medium and large heights.

For more control over the sheet’s presentation, SwiftUI provides additional modifiers like presentationContentInteraction, which configures the behavior of swipe gestures on a presentation, and presentationDragIndicator, which sets the visibility of the drag indicator on top of a sheet.

This is how you can configure a modal’s height in SwiftUI, providing a more interactive and adaptable user experience.

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.