SwiftUI中使用UIKit
程序员文章站
2022-07-03 12:47:23
使用UIViewController实现以下方法@Binding var uiImage: UIImage?@Environment(\.presentationMode) var presentationModefunc makeUIViewController(context: Context) -> UIImagePickerController { let picker = UIImagePickerController() picker.delegate...
使用UIViewController
实现以下方法
@Binding var uiImage: UIImage?
@Environment(\.presentationMode) var presentationMode
func makeUIViewController(context: Context) -> UIImagePickerController {
let picker = UIImagePickerController()
picker.delegate = context.coordinator
return picker
}
func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
// 相册库代理
class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var parent: ImagePickerView
init(_ parent: ImagePickerView) {
self.parent = parent
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let uiImage = info[.originalImage] as? UIImage {
parent.uiImage = uiImage
parent.presentationMode.wrappedValue.dismiss()
}
}
}
在SwiftUI中使用
ImagePickerView(uiImage: self.$uiImage)
回调实现
以保存图片到相册为例
新建一个ImageSaver类,利用闭包进行回调,这也是三方库对外提供服务的常用手段
class ImageSaver: NSObject {
var successHandler: (() -> Void)?
var errorHandler: ((Error) -> Void)?
func save(uiImage: UIImage) {
UIImageWriteToSavedPhotosAlbum(uiImage, self, #selector(saveError), nil)
}
@objc func saveError(_ image: UIImage, _ error: Error?, _ contextInfo: UnsafeRawPointer) {
if let error = error {
errorHandler?(error)
} else {
successHandler?()
}
}
}
使用
Button("保存"){
guard let uiImage = self.uiImage else { return }
let imageSaver = ImageSaver()
imageSaver.successHandler = {
print("保存成功")
}
imageSaver.errorHandler = { error in
print(error.localizedDescription)
}
imageSaver.save(uiImage: uiImage)
}
使用UIView
与使用UIViewController类似的流程
struct MapView: UIViewRepresentable {
func makeUIView(context: Context) -> MKMapView {
return MKMapView()
}
func updateUIView(_ uiView: MKMapView, context: Context) {
}
}
struct MapView_Previews: PreviewProvider {
static var previews: some View {
MapView()
}
}
本文地址:https://blog.csdn.net/wjnhub/article/details/107456435