|
| 1 | +import SwiftUI |
| 2 | + |
| 3 | +/// Пикер для одной фотографии с возможностью обрезки |
| 4 | +public struct SWImagePicker: UIViewControllerRepresentable { |
| 5 | + let completion: (UIImage) -> Void |
| 6 | + @Environment(\.dismiss) private var dismiss |
| 7 | + |
| 8 | + /// Инициализатор |
| 9 | + /// - Parameter completion: Возвращает выбранную фотографию |
| 10 | + public init(completion: @escaping (UIImage) -> Void) { |
| 11 | + self.completion = completion |
| 12 | + } |
| 13 | + |
| 14 | + public func makeUIViewController(context: Context) -> UIImagePickerController { |
| 15 | + let picker = UIImagePickerController() |
| 16 | + picker.sourceType = .photoLibrary |
| 17 | + picker.allowsEditing = true |
| 18 | + picker.delegate = context.coordinator |
| 19 | + return picker |
| 20 | + } |
| 21 | + |
| 22 | + public func updateUIViewController(_: UIImagePickerController, context _: Context) {} |
| 23 | + |
| 24 | + public func makeCoordinator() -> Coordinator { .init(self) } |
| 25 | + |
| 26 | + public final class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate { |
| 27 | + private let parent: SWImagePicker |
| 28 | + |
| 29 | + init(_ parent: SWImagePicker) { |
| 30 | + self.parent = parent |
| 31 | + } |
| 32 | + |
| 33 | + public func imagePickerController( |
| 34 | + _: UIImagePickerController, |
| 35 | + didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any] |
| 36 | + ) { |
| 37 | + if let image = info[.editedImage] as? UIImage ?? info[.originalImage] as? UIImage { |
| 38 | + parent.completion(image) |
| 39 | + } |
| 40 | + parent.dismiss() |
| 41 | + } |
| 42 | + |
| 43 | + public func imagePickerControllerDidCancel(_: UIImagePickerController) { |
| 44 | + parent.dismiss() |
| 45 | + } |
| 46 | + } |
| 47 | +} |
0 commit comments