struct ImagePickerView: UIViewControllerRepresentable {
typealias UIViewControllerType = UIImagePickerController
@Environment(\.presentationMode) var presentationMode
@Binding var image: UIImage?
enum SourceType {
case camera, library
}
var sourceType: SourceType
var allowsEditing: Bool = false
class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
let parent: ImagePickerView
init(_ parent: ImagePickerView) {
self.parent = parent
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
parent.image = info[.editedImage] as? UIImage ?? info[.originalImage] as? UIImage
parent.presentationMode.wrappedValue.dismiss()
}
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIViewController(context: Context) -> UIViewControllerType {
let vc = UIImagePickerController()
vc.delegate = context.coordinator
vc.sourceType = sourceType == .camera ? .camera : .photoLibrary
vc.allowsEditing = allowsEditing
return vc
}
func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {}
}