How do you make a bottom sheet just like in Apple Maps or Find My using UIKit, but using it from SwiftUI?

Asked on 08/02/2024

1 search

To create a bottom sheet similar to those in Apple Maps or Find My using UIKit but from SwiftUI, you can leverage the interoperability between SwiftUI and UIKit. Specifically, you can use UIViewControllerRepresentable to wrap a UIKit view controller and present it as a SwiftUI view.

Here's a step-by-step guide:

  1. Create a UIKit View Controller for the Bottom Sheet: Define a custom UIViewController that will act as your bottom sheet. You can use UISheetPresentationController to manage the sheet's presentation.

  2. Wrap the UIKit View Controller in SwiftUI: Use UIViewControllerRepresentable to create a SwiftUI-compatible wrapper for your custom view controller.

  3. Present the Bottom Sheet in SwiftUI: Use SwiftUI's .sheet modifier to present the wrapped view controller as a bottom sheet.

Example Code

Step 1: Create a UIKit View Controller

import UIKit

class BottomSheetViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        // Add your custom UI elements here
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if let sheet = self.sheetPresentationController {
            sheet.detents = [.medium(), .large()]
            sheet.prefersGrabberVisible = true
        }
    }
}

Step 2: Wrap the UIKit View Controller

import SwiftUI

struct BottomSheetView: UIViewControllerRepresentable {
    func makeUIViewController(context: Context) -> BottomSheetViewController {
        return BottomSheetViewController()
    }
    
    func updateUIViewController(_ uiViewController: BottomSheetViewController, context: Context) {
        // Update the view controller if needed
    }
}

Step 3: Present the Bottom Sheet in SwiftUI

import SwiftUI

struct ContentView: View {
    @State private var showSheet = false
    
    var body: some View {
        VStack {
            Button("Show Bottom Sheet") {
                showSheet.toggle()
            }
        }
        .sheet(isPresented: $showSheet) {
            BottomSheetView()
        }
    }
}

Relevant Sessions

For more details on integrating UIKit with SwiftUI, you can refer to the session SwiftUI essentials which covers SDK interoperability and how to use UIViewControllerRepresentable.

Additional Resources

These sessions provide insights into using UIKit components within SwiftUI and enhancing UI animations and transitions, which can be useful for creating a polished bottom sheet experience.

How do you make a bottom sheet just like in Apple Maps or Find My using UIKit, but using it from SwiftUI? | Ask WWDC