2

For the life of me, I cannot center this bezier path (the circle displayed below). The orange view is properly constrained and horizontally aligned, however when I add 3 layers to the orange view using the method below, I cannot seem to center it to the orange view. I declared the orange view as spinnerHolder.

enter image description here

private func createCircleShapeLayer(strokeColor: UIColor, fillColor: UIColor) -> CAShapeLayer {
    let layer = CAShapeLayer()

    //The farther from 0 x is for this, the more separated the movements of the 3 paths.
    let circularPath = UIBezierPath(
        arcCenter: CGPoint(x: 0, y: 0),
        radius: 30,
        startAngle: 0,
        endAngle: 2 * CGFloat.pi,
        clockwise: true
    )
    layer.path = circularPath.cgPath
    layer.strokeColor = strokeColor.cgColor
    layer.lineWidth = 3
    layer.fillColor = fillColor.cgColor
    layer.lineCap = kCALineCapRound
    layer.position = spinnerHolder.center
    return layer
}
ScottyBlades
  • 12,189
  • 5
  • 77
  • 85

2 Answers2

4

1- Change arcCenter to

let circularPath = UIBezierPath(arcCenter: CGPoint(x:spinnerHolder.frame.width/2, y:spinnerHolder.frame.height/2),
                                radius: 30,
                                startAngle: 0,
                                endAngle: 2 * CGFloat.pi,
                                clockwise: true)

2- Comment this

layer.position = spinnerHolder.center

3- Call the method inside viewDidLayoutSubviews

var once = false
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    if once {
        spinnerHolder.addSublayer(createCircleShapeLayer(,,,,,))
        once = false
    }
}

calling inside viewDidLayoutSubviews isn't mandatory , add it anytime/anywhere but not before the VC loads

4- Check this Centering CAShapeLayer within UIView Swift

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
2

set arcCenter point as

let centerPoint = CGPoint(x:self.viewRect.bounds.midX, y: self.viewRect.bounds.midY)
Dharini
  • 700
  • 7
  • 20