2
votes

I'm new to Swift, and I can't seem to figure out one of the most basic things - setting frame and bounds for a CALayer, so I can read them later.

I'm trying to see where a box is drawn on a CALayer to determine how close to the center of the layer it is.

I would have assumed the CALayer is the same size of the layer/view it's added to with subview, but when I look at the CALayer's frame or bounds it's zero. Same for the superview layer/view.

Any help would be much appreciated!

Goal: check where a box is written within a layer

Pseudo Code:

create new layer
draw a box on layer
look at box dimensions and compare to layer dimensions
if box near middle of the layer then print success

View/Layer Hierarchy (top to bottom)

 1. CALayer named shapeLayer
 2. CALayer named previewLayer (this is a AVCaptureVideoPreviewLayer)
 3. UIView named videoPreview

I can't set frame or bounds for any of the 3 views/layers. All i get is 0 back when I read the frame or bounds value.

Note, I've tried calling code in viewWillAppear as well, but same result.

override func viewDidLoad() {
    super.viewDidLoad()
    if let previewLayer = self.videoCapture.previewLayer {
        self.videoPreview.layer.addSublayer(previewLayer)
        videoCapture.previewLayer?.frame = videoPreview.bounds
    }

    if videoCapture.previewLayer?.frame != nil {

        videoCapture.previewLayer!.frame = CGRect(x:0, y:0, width:375, height: 667)

        let w = videoCapture.previewLayer!.frame.height
        let h = videoCapture.previewLayer!.frame.width

        NSLog("Print the height and width  w:%i, h:%i", w, h);

    }   
}
1
The answer is correct - you are looking too early for frame values. You might be able to check as soon as viewWillLayoutSubviews, but setting frames in viewDidLoad is very risky at best. (As opposed to setting auto layout constraints.) Also, something that - I believe - most developers would say is you have your hierarchy backwards. "Top" usually mean the "parent" or "root", and "bottom" usually means "subviews" or "sublayers".dfd

1 Answers

3
votes

You will get the frame of your layers when the view did layout its subviews:

override func viewDidLoad() {
    super.viewDidLoad()
    if let previewLayer = self.videoCapture.previewLayer {
        self.videoPreview.layer.addSublayer(previewLayer)
    }
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    if let previewLayer = self.videoCapture.previewLayer {
        videoCapture.previewLayer?.frame = videoPreview.bounds
    }

    if videoCapture.previewLayer?.frame != nil {

        videoCapture.previewLayer!.frame = CGRect(x:0, y:0, width:375, height: 667)

        let w = videoCapture.previewLayer!.frame.height
        let h = videoCapture.previewLayer!.frame.width

        NSLog("Print the height and width  w:%i, h:%i", w, h)
    }
}