Skip to content

Instantly share code, notes, and snippets.

@mdb1
Created January 30, 2024 22:53
Show Gist options
  • Save mdb1/7fce7f08155bffb17560757bc06ec4bc to your computer and use it in GitHub Desktop.
Save mdb1/7fce7f08155bffb17560757bc06ec4bc to your computer and use it in GitHub Desktop.
SwiftUI Wrapper for UIImagePickerController.
import SwiftUI
/// SwiftUI Wrapper for UIImagePickerController.
struct ImagePicker: UIViewControllerRepresentable {
var sourceType: UIImagePickerController.SourceType = .photoLibrary
@Binding var selectedImage: UIImage?
@Environment(\.dismiss) private var dismiss
func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController {
let imagePicker = UIImagePickerController()
imagePicker.allowsEditing = true
imagePicker.sourceType = sourceType
if sourceType == .camera {
imagePicker.showsCameraControls = true
}
imagePicker.delegate = context.coordinator
return imagePicker
}
func updateUIViewController(
_: UIImagePickerController,
context _: UIViewControllerRepresentableContext<ImagePicker>
) {}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
final class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var parent: ImagePicker
init(_ parent: ImagePicker) {
self.parent = parent
}
func imagePickerController(
_: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]
) {
if let image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
withAnimation {
parent.selectedImage = image
}
}
parent.dismiss()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment