Search code examples
swiftavfoundationcalayerswift5

No way to add a view over a AVCaptureVideoPreviewLayer using StoryBoard?


I have seen other questions about this on SO, but mine is different because I am looking for a solution using a structure previously created using storyboard.

I need to have a StackView over a AVCaptureVideoPreviewLayer.

I have a view like this:

enter image description here

I need to create a AVCaptureVideoPreviewLayer in a way that puts this layer below the Stack Control you see on the previous picture.

My AVCaptureVideoPreviewLayer WAS created like this:

let cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
cameraPreviewLayer.videoGravity = .resizeAspectFill
cameraPreviewLayer.connection?.videoOrientation = .portrait
cameraPreviewLayer.frame = view.frame
view.layer.insertSublayer(cameraPreviewLayer, at: 0)

But to make sure the layer would be created at the current position, I've created this Preview View below Stack Control (see picture).

The idea is to add AVCaptureVideoPreviewLayer to that view.

So, I changed the code to:

let cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
cameraPreviewLayer.videoGravity = .resizeAspectFill
cameraPreviewLayer.connection?.videoOrientation = .portrait
cameraPreviewLayer.frame = view.frame
previewView.layer.insertSublayer(cameraPreviewLayer, at: 0)

have also tried

previewView.layer.addSublayer(cameraPreviewLayer)

No way, the preview shows fine but Stack Control is not there. I see the stack if I do not insert the AVCaptureVideoPreviewLayer.

Any ideas?


Solution

  • What you need to do is,

    1. take AVCapturePreviewLayer, and add it as a sublayer to the PreviewView.

      PreviewView.layer.addSublayer(cameraPreviewLayer)

    2. Add previewView as a subView to the parent View

      view.addSubview(PreviewView)

    3. and add StackControl as a subview to the parent View

      view.addSubview(StackControl)