142 - Control Interaction with the View Behind a Modal in SwiftUI

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.

In this example:

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.