Search code examples
iosiphoneswiftoverlayavcapture

Add UIButton over AVCaptureVideoPreviewLayer programmatically


I am trying to create a overlay on top of AVCaptureVideoPreviewLayer.

I tried the following, but the result is not what I expected as the button's title is not visible:

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)

Here is a screenshot of the current state:

screenshot of the current state


Solution

  • You should add previewLayer to a separate view's sublayer. That way, you can easily add other subviews above your main view.

    let previewView = UIView(frame: view.frame)
    view.addSubview(previewView)
    
    previewView.layer.addSublayer(previewLayer)
    
    [...]
    
    view.addSubview(captureButton)