Why does the Coordinator for UIViewRepresentable written so verbose? Given below are two fragments of code, one using UIViewRepresentable and one using UIViewControllerRepresentable:
struct CustomCameraView: UIViewControllerRepresentable {
func makeUIViewController(context: Context) -> CustomCameraViewController {
...
}
func updateUIViewController(_ uiViewController: CustomCameraViewController, context: Context) {
...
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject {
var parent: CustomCameraView
init(_ parent: CustomCameraView) {
self.parent = parent
}
}
}
And with UIViewRepresentable:
struct CustomCameraView: UIViewRepresentable {
func makeUIView(context: Context) -> CustomUIView {
...
}
func updateUIView(_ uiView: CustomUIView, context: Context) -> CustomUIView {
...
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject {
var parent: CustomCameraView
init(_ parent: CustomCameraView) {
self.parent = parent
}
}
}
The UIViewRepresentable code complains about the following two things:
- Nested class
CustomCameraView.Coordinatorhas an unstable name when archiving viaNSCoding. - Type
CustomCameraView.Coordinatordoes not conform to the protocolNSCoding.
There are automatic ways to fix it:
@objc(CustomCameraView_Coordinator) class Coordinator: NSObject {
var parent: CustomCameraView
init(_ parent: CustomCameraView) {
self.parent = parent
}
func encode(with Coder: NSCoder) {
...
}
required init?(coder: NSCoder) {
...
}
}
My question is that, why does Coordinator work with UIViewControllerRepresentable but complains about these errors in UIViewRepresentable? Are the Coordinators for these implemented differently?
Coordinator()instead ofCoordinator(self).selfis value that will change when the view data changes so you can't hang on to it like it is an object reference.