Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Add a List to a Modal in SwiftUI
Written by Team Kodeco

When you have a scroll view or a list within a modal in SwiftUI, controlling the behavior of swipe gestures can be important for the user experience. The presentationContentInteraction modifier allows you to configure how the swipe gesture behaves in this context.

By default, when a person swipes up on a scroll view in a resizable presentation, the presentation grows to the next detent. A scroll view embedded in the presentation only scrolls after the presentation reaches its largest size.

However, you can modify this behavior so that swipe gestures on the scroll view content take precedence over resizing the sheet. You can do this by passing the .scrolls value to the presentationContentInteraction modifier. This means the content scrolls first when the user swipes up, and the sheet only resizes after hitting the end of the scroll view.

Here’s an example of adding a list to a modal and configuring the swipe gesture behavior:

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

  var body: some View {
    Button("Show Modal") {
      showModal = true
    }
    .sheet(isPresented: $showModal) {
      VStack {
        List(0..<50) { item in
          Text("Item \(item)")
        }
      }
      .presentationDetents([.medium, .large])
      .presentationContentInteraction(.scrolls)
    }
  }
}

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

A modal view with a list in SwiftUI.
A modal view with a list in SwiftUI.

In this example, you create a button that, when pressed, presents a modal sheet containing a list. By setting .presentationContentInteraction(.scrolls), you ensure that when the user swipes up on the list, it scrolls rather than resizing the sheet to its next detent.

When .presentationContentInteraction(.scrolls) is set, the user must resize the sheet using the drag indicator. This control is always available regardless of the content interaction behavior set.

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.