0
votes

I have an animation for drawing a circle. I combine 3 different circle animations to create a stylised graph/pie chart.

They animate perfection when in an @IBAction from a button. But how would I start the animation automatically when the Storyboard/ViewController is opened/navigated to?

Animation code as follows:

    //NF Colour
    let colorNF = UIColor(red: 28/255, green: 117/255, blue: 189/255, alpha: 1)

    // Create Holding Rectangle and Start and End Angles
    let ovalStartAngleNF = CGFloat(-90.01 * .pi/180)
    let ovalEndAngleNF = CGFloat(10.0 * .pi/180)
    let ovalRectNF = CGRect(origin: CGPoint(x: 122.5,y: 83.5), size: CGSize(width: 100, height: 100))

    // Create Bezier Path
    let ovalPathNF = UIBezierPath()

    // Apply Attributes to Bezier Path
    ovalPathNF.addArc(withCenter: CGPoint(x: ovalRectNF.midX, y: ovalRectNF.midY),
                      radius: ovalRectNF.width / 2,
                      startAngle: ovalStartAngleNF,
                      endAngle: ovalEndAngleNF, clockwise: true)

    // Styling of the Curve
    let progressLineNF = CAShapeLayer()
    progressLineNF.path = ovalPathNF.cgPath
    progressLineNF.strokeColor = colorNF.cgColor
    progressLineNF.fillColor = UIColor.clear.cgColor
    progressLineNF.lineWidth = 20.0
    progressLineNF.lineCap = kCALineCapRound

    // Add Curve to Viewport
    self.view.layer.addSublayer(progressLineNF)

    // Animated the 'Stroke End' from 0 to 1 over 3 Seconds
    let animateStrokeEndNF = CABasicAnimation(keyPath: "strokeEnd")
    animateStrokeEndNF.duration = 3.0
    animateStrokeEndNF.fromValue = 0.0
    animateStrokeEndNF.toValue = 1.0

    // Add the Animation to the Progress Line
    progressLineNF.add(animateStrokeEndNF, forKey: "animate stroke end animation")
1
move your animation code to your viewDidLoad. - Joe
@Joe I've just tried doing that, and the circles are drawn out instantly, instead of animating from 0 to 1. Any other ideas? - Ryan Elliott
try change your animation duration to higher value > 3 (animateStrokeEndNF.duration = 10.0) and try moving your code to viewDidAppear or viewWillAppear to create some startup delay? - Joe
@Joe I've just tried what you mentioned, and while the animation code is inside 'func viewDidAppear() { super.viewDidAppear(true) }' it disappears when running in the simulator. I'm relatively new to Swift, so apologies for my lack of understanding! - Ryan Elliott
tested your code it looks ok in simulator.try your code in override func viewWillAppear(_ animated: Bool) {} - Joe

1 Answers

0
votes

As stated by Joe in the comments. The solution was to place my animation code into a viewWillAppear.

 override func viewWillAppear(_ animated: Bool) { *ANIMATION CODE* }