Created
January 30, 2024 22:53
-
-
Save mdb1/7fce7f08155bffb17560757bc06ec4bc to your computer and use it in GitHub Desktop.
SwiftUI Wrapper for UIImagePickerController.
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 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