Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Control Interaction with the View Behind a Modal in SwiftUI
Written by Team Kodeco

In SwiftUI, by default, the view behind a modal presentation (such as a sheet or a popover) is disabled to prevent user interactions. This means that while the modal is presented, you cannot interact with the views behind the modal. However, SwiftUI provides the presentationBackgroundInteraction modifier that can be used to control the interaction with the view behind a modal.

The following SwiftUI example showcases how to use presentationBackgroundInteraction:

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

  var body: some View {
    VStack {
      Color(hue: hueValue, saturation: 0.5, brightness: 1.0)
        .frame(width: 200, height: 200)
        .cornerRadius(10)
        .padding()

      Slider(value: $hueValue, in: 0...1)
        .padding()

      Button("Show Joke") {
        showModal = true
      }
      .sheet(isPresented: $showModal) {
        VStack {
          Text("Why don't scientists trust atoms?")
          Text("Because they make up everything!")
        }
        .presentationDetents([.height(120), .medium, .large])
        .presentationBackgroundInteraction(.enabled(upThrough: .height(120)))
        .presentationBackground {
          Color.orange.opacity(0.8)
        }
      }
    }
  }
}

Tap the Show Joke button, then experiment with the slider. Your preview should look like this:

A modal view with a joke where you can interact with the background in SwiftUI.
A modal view with a joke where you can interact with the background in SwiftUI.

In this example:

  • You start with a main view that has a colorful square and a slider. You can adjust the hue of the square using the slider.
  • When you tap the Show Joke button, a modal with a joke is presented.
  • You apply the presentationBackgroundInteraction(_:) modifier to the modal. This allows you to interact with the view behind the modal when it’s at the smallest height. But when the modal is at medium or large heights, the interaction with the background becomes disabled.

In summary, the presentationBackgroundInteraction modifier enables you to control whether or not the view behind a modal is interactive, providing flexibility in the user experience of your app.

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.