0

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:

  1. Nested class CustomCameraView.Coordinator has an unstable name when archiving via NSCoding.
  2. Type CustomCameraView.Coordinator does not conform to the protocol NSCoding.

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?

2
  • I'm using Xcode 16 and can compile your code succesfully Commented Nov 25, 2024 at 6:45
  • Not sure if it is the cause of the issue but it should be Coordinator() instead of Coordinator(self). self is value that will change when the view data changes so you can't hang on to it like it is an object reference. Commented Nov 25, 2024 at 13:12

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.