我需要在我的应用程序中使用SwiftUI打开一个图像 Select 器,我该怎么做?

我考虑过使用UIImagePickerController,但我不知道如何在SwiftUI中使用.

推荐答案

Xcode 12的清理版可通过SPM作为Swift软件包提供:

https://github.com/ralfebert/ImagePickerView

资料来源:

import SwiftUI

public struct ImagePickerView: UIViewControllerRepresentable {

    private let sourceType: UIImagePickerController.SourceType
    private let onImagePicked: (UIImage) -> Void
    @Environment(\.presentationMode) private var presentationMode

    public init(sourceType: UIImagePickerController.SourceType, onImagePicked: @escaping (UIImage) -> Void) {
        self.sourceType = sourceType
        self.onImagePicked = onImagePicked
    }

    public func makeUIViewController(context: Context) -> UIImagePickerController {
        let picker = UIImagePickerController()
        picker.sourceType = self.sourceType
        picker.delegate = context.coordinator
        return picker
    }

    public func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {}

    public func makeCoordinator() -> Coordinator {
        Coordinator(
            onDismiss: { self.presentationMode.wrappedValue.dismiss() },
            onImagePicked: self.onImagePicked
        )
    }

    final public class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {

        private let onDismiss: () -> Void
        private let onImagePicked: (UIImage) -> Void

        init(onDismiss: @escaping () -> Void, onImagePicked: @escaping (UIImage) -> Void) {
            self.onDismiss = onDismiss
            self.onImagePicked = onImagePicked
        }

        public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
            if let image = info[.originalImage] as? UIImage {
                self.onImagePicked(image)
            }
            self.onDismiss()
        }

        public func imagePickerControllerDidCancel(_: UIImagePickerController) {
            self.onDismiss()
        }

    }

}

Swift相关问答推荐

如何为任务扩展的泛型静态函数获得自动类型推理

在SwiftUI中判断选项时避免重复查看

SwiftData/PersistentModel.swft:540:致命错误:不支持的关系密钥路径ReferenceWritableKeyPath

try 从闭包访问返回的字符串时出现无法将类型 '()' 的返回表达式转换为返回类型 'String'编译器错误

应该在ViewModel还是ViewController中使用"Task {}"?

设备上ScrollView为什么会将内容高度更改为随机值,而在预览上不会? - 优化后的标题:设备上ScrollView内容高度随机变化问题解决

使用异步收集发布者值

类型擦除`AsyncMapSequence, Element>`

有没有更快的方法来循环浏览 macOS 上已安装的应用程序?

关于变量的视图的 SwiftUI 生命周期

闭包 - deinit self 对象的时间

如何将回调传递给 View init

Xcode swift ui 错误KeyPathComparator仅在 macOS 12.0 或更高版本中可用

'#selector' 的参数不引用 '@objc' 方法、属性或初始化程序

CMutablePointer - 如何访问它?

如何在 Swift 中遍历 struct 属性?

为什么'nil' 与 Swift 3 中的 'UnsafePointer' 不兼容?

如何在 Swift 中使用 Crashlytics 登录?

Swift 5 秒后关闭 UIAlertView

iOS:如何检测用户是否订阅了自动更新订阅