ios – Type does not conform to protocol ‘UIViewRepresentable’


The problem is that the associated type UIViewType could not be inferred.

You can see the detailed error when you look at the Issue Navigator (⌘5)

enter image description here

The actual problem is that AVCaptureVideoPreviewLayer does not inherit from UIView which is a protocol constraint.

According to the suggestion in Duncan’s comment and the documentation of AVCaptureVideoPreviewLayer wrap the layer in an UIView

class PreviewView: UIView {
    // Use a capture video preview layer as the view's backing layer.
    override class var layerClass: AnyClass {
        AVCaptureVideoPreviewLayer.self
    }
    
    var previewLayer: AVCaptureVideoPreviewLayer {
        layer as! AVCaptureVideoPreviewLayer
    }
    
    // Connect the layer to a capture session.
    var session: AVCaptureSession? {
        get { previewLayer.session }
        set { previewLayer.session = newValue }
    }
}

and change CameraPreview to

struct CameraPreview: UIViewRepresentable {
    var session: AVCaptureSession

    func makeUIView(context: Context) -> PreviewView {
        let previewView = PreviewView()
        previewView.session = self.session
        previewView.previewLayer.videoGravity = .resizeAspectFill
        return previewView
    }

    func updateUIView(_ uiView: PreviewView, context: Context) {
        // Update the preview layer if needed
    }
}

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img