Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Pass Data to a Modal View in SwiftUI
Written by Team Kodeco

Passing data between views is a common need in many applications. In SwiftUI, you can easily pass data from a parent view to a child view. When it comes to modal views, this can be especially useful to display additional information or to collect user inputs.

In this entry, you’ll learn how to pass data to a modal view using SwiftUI. You will create a list of products and present a detail view for the selected product.

struct Product {
  let name: String
  let price: Int
}

extension Product: Identifiable { var id: String { name }}

struct ProductDetailView: View {
  let product: Product

  var body: some View {
    VStack {
      Text(product.name)
        .font(.title)
      Text("Price: \(product.price)")
    }
  }
}

struct ContentView: View {
  let products = [
    Product(name: "Macbook Pro", price: 1299),
    Product(name: "iPhone", price: 999),
    Product(name: "AirPods", price: 199)
  ]

  @State private var selectedProduct: Product?

  var body: some View {
    List(products) { product in
      Text(product.name)
        .onTapGesture {
          selectedProduct = product
        }
    }
    .sheet(item: $selectedProduct, content: { product in
      ProductDetailView(product: product)
    })
  }
}

Tap the iPhone row and your preview should look like this:

Pass data to a modal view in SwiftUI.
Pass data to a modal view in SwiftUI.

In this example, you have a list of products displayed in a ContentView. When a product is tapped, you assign it to selectedProduct, which triggers the modal to show the details for that specific product.

The sheet(item:content:) modifier is used here. This version of the sheet modifier takes an Identifiable item, and only presents the modal when this item isn’t nil. When the modal is dismissed, the item is automatically set back to nil. This automatic handling simplifies the logic needed to show and dismiss the modal.

With this knowledge, you can now pass data to a modal view in SwiftUI with ease, improving the flexibility and usability of your apps.

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.