Search code examples
iosswiftcashapelayer

How to centre my CAShapeLayer within UIView - Swift?


I am trying to create a loading progress circle popup with a UIViewController. I am having issues trying to get my circle within a UIView that is a subView of the parent view. Please can someone advice?

I am trying to create a loading progress circle popup with a UIViewController. I am having issues trying to get my circle within a UIView that is a subView of the parent view. Please can someone advice?

enter image description here

 let shapeLayer = CAShapeLayer()

let percentageLabel: UILabel = {
    let label = UILabel()
    label.text = "Start"
    label.textAlignment = .center
    label.font = UIFont.boldSystemFont(ofSize: 32)
    return label
}()


 override func viewDidLoad() {
    super.viewDidLoad()

    createObserver()

    self.poUpOutlet.addSubview(percentageLabel)
    percentageLabel.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
    percentageLabel.center = self.poUpOutlet.center

    let trackLayer = CAShapeLayer()

    let circularPath = UIBezierPath(arcCenter: .zero, radius: 50, startAngle: 0, endAngle: 2 * CGFloat.pi, clockwise: true)
    trackLayer.path = circularPath.cgPath

    trackLayer.strokeColor = UIColor.lightGray.cgColor
    trackLayer.lineWidth = 10
    trackLayer.fillColor = UIColor.clear.cgColor
    trackLayer.lineCap = kCALineCapRound
    trackLayer.position = self.poUpOutlet.center

    self.poUpOutlet.layer.addSublayer(trackLayer)

    shapeLayer.path = circularPath.cgPath

    shapeLayer.strokeColor = UIColor.red.cgColor
    shapeLayer.lineWidth = 10
    shapeLayer.fillColor = UIColor.clear.cgColor
    shapeLayer.lineCap = kCALineCapRound
    shapeLayer.position = self.poUpOutlet.center

    shapeLayer.transform = CATransform3DMakeRotation(-CGFloat.pi / 2, 0, 0, 1)

    shapeLayer.strokeEnd = 0

    self.poUpOutlet.layer.addSublayer(shapeLayer)
}

Solution

  • Replace 3 occurances of

    self.poUpOutlet.center
    

    in your code with:

    self.poUpOutlet.convert(self.poUpOutlet.center, from: self.poUpOutlet.superview)
    

    then it should work.