以编程方式在 AVCaptureVideoPreviewLayer 上添加 UIButton

Add UIButton over AVCaptureVideoPreviewLayer programmatically

我正在尝试在 AVCaptureVideoPreviewLayer 上创建叠加层。

我尝试了以下方法,但结果不是我预期的,因为按钮的标题不可见:

let previewLayer: AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.avCaptureSession)
previewLayer.frame = self.view.layer.frame
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
self.view.layer.addSublayer(previewLayer)



//Add Button
let captureButton = UIButton(frame: CGRectMake(0, 0, 100 , 100))
captureButton.backgroundColor = UIColor.grayColor()
captureButton.setTitle("Capture", forState: .Normal)
captureButton.setTitleColor(UIColor.redColor(), forState: .Normal)
captureButton.addTarget(self, action: "actionCapture:", forControlEvents: .TouchDragInside)

previewLayer.addSublayer(captureButton.layer)

这是当前状态的屏幕截图:

您应该将 previewLayer 添加到单独视图的子层。这样,您就可以轻松地在主视图上方添加其他子视图。

let previewView = UIView(frame: view.frame)
view.addSubview(previewView)

previewView.layer.addSublayer(previewLayer)

[...]

view.addSubview(captureButton)