SwiftUI UIViewControllerRepresentable,Coordinator(self) 是什么意思?

SwiftUI UIViewControllerRepresentable, what does Coordinator(self) mean?

在制作 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) {
        
    }
}

self 始终表示“当前实例”。所以当你写...

struct ImagePicker: UIViewControllerRepresentable {
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
}

... self 表示“此 ImagePicker 实例”。

你这样说是因为 Coordinator 的初始值设定项的声明方式:

class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    var parent: ImagePicker
    init(_ parent: ImagePicker) {
        self.parent = parent
    }
}

协调器需要 parent 才能初始化;你正在初始化一个协调器,你告诉parent应该是谁,即(即 self,这个 ImagePicker)。

如果这些概念给您带来麻烦,您可能需要研究什么是类型和实例(面向对象编程)and/orSwift 初始化器和初始化是如何表达的。