【SwiftUI】图片选择器 ImagePicker的包装
发表于更新于
广州
开发swiftui【SwiftUI】图片选择器 ImagePicker的包装
❄️2winter由于目前SwiftUI还未实现这个组件,所以需要使用UIkit的组件包装后在Swiftui使用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| import UIKit import SwiftUI struct ImagePicker: UIViewControllerRepresentable {
@Environment(\.presentationMode) private var presentationMode
let sourceType: UIImagePickerController.SourceType let onImagePicked: (UIImage) -> Void
final class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@Binding private var presentationMode: PresentationMode private let sourceType: UIImagePickerController.SourceType private let onImagePicked: (UIImage) -> Void
init(presentationMode: Binding<PresentationMode>, sourceType: UIImagePickerController.SourceType, onImagePicked: @escaping (UIImage) -> Void) { _presentationMode = presentationMode self.sourceType = sourceType self.onImagePicked = onImagePicked }
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { let uiImage = info[UIImagePickerController.InfoKey.originalImage] as! UIImage onImagePicked(uiImage) presentationMode.dismiss()
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { presentationMode.dismiss() }
}
func makeCoordinator() -> Coordinator { return Coordinator(presentationMode: presentationMode, sourceType: sourceType, onImagePicked: onImagePicked) }
func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController { let picker = UIImagePickerController() picker.sourceType = sourceType picker.delegate = context.coordinator return picker }
func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePicker>) {
}
}
|
使用
在swift的布局里初始化两个变量,一个控制选择器状态,一个获取选择的图片
1 2
| @State var showImagePicker: Bool = false @State var image: Image? = nil
|
1 2 3 4 5
| .sheet(isPresented: $showImagePicker) { ImagePicker(sourceType: .photoLibrary) { image in self.image = Image(uiImage: image) } }
|
现在swiftui还是不完善,希望能够尽快完善一下,不然我还要重头学习UIKit。
❄️2winter
ReactNative FullStack Developer
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 ❄️2winter!