在Swift中将子图层调整为UIView范围

时间:2019-03-08 19:36:43

标签: ios swift layout sublayout

我正在尝试将AVCaptureVideoPreviewLayer作为UIView元素中的子层。我尝试使用以下方法将其框架设置为UIView边界:

cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
cameraPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
cameraPreviewLayer?.connection?.videoOrientation = AVCaptureVideoOrientation.portrait
cameraPreviewLayer?.frame = PreviewController.bounds
PreviewController.layer.addSublayer(cameraPreviewLayer!)

当我尝试打印框架的值和边界时,它会显示以下信息:

print(PreviewController.bounds)
print(cameraPreviewLayer!.frame)

(0.0, 0.0, 375.0, 500.0)
(0.0, 0.0, 375.0, 500.0)

在实际的应用程序中,它导致子层无法填充整个UIView元素:

Error

有人知道如何解决吗?

1 个答案:

答案 0 :(得分:0)

您需要

override func viewDidLayoutSubviews() {
  super.viewDidLayoutSubviews()
  cameraPreviewLayer?.frame = PreviewController.bounds
}