Search code examples
ioscashapelayer

Aligning CAShapeLayer center of my UIView


I've been trying to solve this for days, and none of the suggestions solved my problem. I have a UIView inside a UITableView. I've been trying to draw my CAShapeLayer inside my UIView, but I just can't get it right.

I need my yellow CAShapeLayer to be exactly center within the gray UIView.

func DrawActivityRect(cell: CalorieDashboardTVCell){
    let rectangle = UIBezierPath(rect: cell.calorieBurnUIView.bounds)

    let trackLayer = CAShapeLayer()
    trackLayer.frame = cell.calorieBurnUIView.bounds
    trackLayer.path = rectangle.cgPath
    trackLayer.position = cell.calorieBurnUIView.center
    trackLayer.strokeColor = UIColor.yellow.cgColor
    trackLayer.lineWidth = 10
    trackLayer.fillColor = UIColor.clear.cgColor
    trackLayer.lineCap = kCALineCapRound
    cell.calorieBurnUIView.layer.addSublayer(trackLayer)
}

Result: enter image description here


Solution

  • I suspect the cell size change after you have set the layer. The easiest place to fix this is in the cell's layoutSubviews(). Since your path is using absolute coordinates you need to update both the layer frame and the path.

    override func layoutSubviews() {
        super.layoutSubviews()
    
        // You need to keep trackLayer around after you created it
        let rectangle = UIBezierPath(rect: cell.calorieBurnUIView.bounds)
        self.trackLayer.frame = cell.calorieBurnUIView.bounds
        self.trackLayer.path = rectangle.cgPath
        self.trackLayer.position = cell.calorieBurnUIView.center
    }