Skip to content

Instantly share code, notes, and snippets.

@scriptpapi
Created April 26, 2021 21:26
Show Gist options
  • Save scriptpapi/01a35cda92066bddcf56cd17375e8679 to your computer and use it in GitHub Desktop.
Save scriptpapi/01a35cda92066bddcf56cd17375e8679 to your computer and use it in GitHub Desktop.
ImagePicker for SwiftUI
import Foundation
import SwiftUI
struct ImagePicker: UIViewControllerRepresentable {
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
@Environment(\.presentationMode) var presentationMode
@Binding var image: UIImage?
func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController {
let picker = UIImagePickerController()
picker.delegate = context.coordinator
return picker
}
func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePicker>) {
}
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 uiImage = info[.originalImage] as? UIImage {
parent.image = uiImage
}
parent.presentationMode.wrappedValue.dismiss()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment