'SubLayer overflowing root layer in iOS storyboards

I have a sublayer (preview layer) which I programmatically set as the proof layer in Swift for a storyboard that overflows the root layer. I intend the video feed to stay inside the root view (red box) however, I can't set it.

Current view of the application

Below is the code

        previewLayer = AVCaptureVideoPreviewLayer(session: session)
//        previewLayer.videoGravity = AVLayerVideoGravity.resize // feed goes off the screen
//        previewLayer.videoGravity = AVLayerVideoGravity.resizeAspect //feed goes off the screen at bottom left corner
        previewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill// same result as resize
        
        
        if (previewLayer.connection!.isVideoMirroringSupported) {
            previewLayer.connection!.automaticallyAdjustsVideoMirroring = false
            previewLayer.connection!.isVideoMirrored = true
        }
        
        let exifOrientation = exifOrientationFromDeviceOrientation()
        
        rootLayer = self.layer
        previewLayer.setAffineTransform(CGAffineTransform(rotationAngle: degreeToRadian(90)).scaledBy(x: 1.0, y: -1.0))
        
        previewLayer.frame = rootLayer.bounds
        rootLayer.addSublayer(previewLayer)
//        self.rootLayer.insertSublayer(previewLayer, at: 0)//yeild same problem

further when comparing the size of self and root layer they appear to be the same:

rootLayer.bounds = height = 1188.0 width = 607.0 self : height 1188.0 width = 607.0


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source