Created
April 26, 2021 21:26
-
-
Save scriptpapi/01a35cda92066bddcf56cd17375e8679 to your computer and use it in GitHub Desktop.
ImagePicker for SwiftUI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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