在制作 UIViewControllerRepresentable(在 SwiftUI 中使用 UIKit 组件)时,Coordinator(self) 意味着什么? 我对“自我”代表什么有点困惑。
import SwiftUI
struct ImagePicker: UIViewControllerRepresentable {
@Binding var image: UIImage?
@Environment(\.presentationMode) var presentationMode
class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var parent: ImagePicker
init(_ parent: ImagePicker) {
self.parent = parent
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let uiImage = info[.originalImage] as? UIImage {
parent.image = uiImage
}
parent.presentationMode.wrappedValue.dismiss()
}
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIViewController(context: Context) -> UIImagePickerController {
let picker = UIImagePickerController()
picker.delegate = context.coordinator
return picker
}
func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {
}
}
Coordinator(self)
是一个错误。 self
表示 SwiftUI 更新后立即丢弃的结构,因此协调器对象挂在它上面是没有意义的。任何对 self
的函数调用都不会执行任何操作。正确的方法是 Coordinator()
,Apple 的 Fruta 示例中的
PaymentButton.swift
中有一个示例。通过此更改,您的代码将类似于:
import SwiftUI
struct ImagePicker: UIViewControllerRepresentable {
@Binding var image: UIImage?
@Environment(\.presentationMode) var presentationMode
func makeCoordinator() -> Coordinator {
Coordinator()
}
func makeUIViewController(context: Context) -> UIImagePickerController {
context.coordinator.imagePicker
}
func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {
context.coordinator.didPickImage = { image in
self.image = image
}
}
class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
lazy var imagePicker: UIImagePickerController = {
let picker = UIImagePickerController()
picker.delegate = self
return picker
}()
var didPickImage: ((Void) -> UIImage)?
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let uiImage = info[.originalImage] as? UIImage {
didPickImage?(uiImage)
}
}
}
}
self
始终表示“当前实例”。所以当你写...
struct ImagePicker: UIViewControllerRepresentable {
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
}
...
self
表示“此 ImagePicker 实例”。
您这样说是因为协调器的初始化程序的声明方式:
class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var parent: ImagePicker
init(_ parent: ImagePicker) {
self.parent = parent
}
}
协调器需要一个
parent
才能初始化;你正在初始化一个协调器,并且你告诉它parent
应该是谁,即你(即self
,这个ImagePicker)。
如果这些概念给您带来麻烦,您可能需要研究什么是类型和实例(面向对象编程)和/或 Swift 初始化器和初始化是如何表达的。