This project demonstrates how to integrate UIKit components inside a SwiftUI app using UIViewControllerRepresentable.
We use UIImagePickerController as a real-world example to allow users to pick an image from their photo library.
- SwiftUI-based layout
- UIKit interoperability using
UIViewControllerRepresentable - Image picker wrapped as a reusable SwiftUI component
- Reactive data flow using
@Binding
import SwiftUI
import UIKit
struct ImagePicker: UIViewControllerRepresentable {
@Environment(\.presentationMode) var presentationMode
@Binding var selectedImage: UIImage?
var sourceType: UIImagePickerController.SourceType = .photoLibrary
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIViewController(context: Context) -> UIImagePickerController {
let picker = UIImagePickerController()
picker.delegate = context.coordinator
picker.sourceType = sourceType
return picker
}
func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {}
class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
let parent: ImagePicker
init(_ parent: ImagePicker) {
self.parent = parent
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[.originalImage] as? UIImage {
parent.selectedImage = image
}
parent.presentationMode.wrappedValue.dismiss()
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
parent.presentationMode.wrappedValue.dismiss()
}
}
}