Reputation: 6597
I currently have a Swift application that changes the fill colour of a square from red to green. What I would like to happen is, when the animation has finished, I would then like to execute some more code.
Here is my file:
import UIKit
class PathViewController: TapToCloseViewController {
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let tempView = UIView(frame: CGRectMake(0,0,100,100))
tempView.layer.borderColor = UIColor.blackColor().CGColor
tempView.layer.borderWidth = 2
view.addSubview(tempView)
let bounds = CGRect(x: 0, y: 0, width: 100, height: 100)
// Create CAShapeLayerS
let rectShape = CAShapeLayer()
rectShape.bounds = bounds
rectShape.position = tempView.center
rectShape.cornerRadius = bounds.width / 2
tempView.layer.addSublayer(rectShape)
tempView.backgroundColor = UIColor.redColor()
// Apply effects here
// fill with white
rectShape.fillColor = UIColor.greenColor().CGColor
// 1
// begin with a circle with a 50 points radius
//let startShape = UIBezierPath(roundedRect: bounds, cornerRadius: 50).CGPath
let sRect = CGRect(x:0, y:0, width: 0, height: bounds.height)
let bpath = UIBezierPath(rect: sRect).CGPath
// animation end with a large circle with 500 points radius
let drect = CGRect(x:0, y:0, width: bounds.width, height: bounds.height)
let endShape = UIBezierPath(rect: drect).CGPath
//let endShape = UIBezierPath(roundedRect: CGRect(x: -450, y: -450, width: 1000, height: 1000), cornerRadius: 500).CGPath
// set initial shape
rectShape.path = bpath
// 2
// animate the `path`
let animation = CABasicAnimation(keyPath: "path")
animation.toValue = endShape
animation.duration = 1 // duration is 1 sec
// 3
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) // animation curve is Ease Out
animation.fillMode = kCAFillModeBoth // keep to value after finishing
animation.removedOnCompletion = false // don't remove after finishing
// 4
rectShape.addAnimation(animation, forKey: animation.keyPath)
}
}
How would I detect when the animation stopped?
Upvotes: 2
Views: 1689
Reputation: 16302
You could set yourself as the delegate
of the animation:
let animation = CABasicAnimation(keyPath: "path")
.....
animation.delegate = self
And subsequently implement the following method:
override func animationDidStop(anim: CAAnimation, finished flag: Bool)
{
NSLog("My beautiful animation has finished.")
}
Upvotes: 5
Reputation: 1757
To animate color change use this
UIView.animateWithDuration(0.3, animations: { () -> Void in
aView.backgroundColor = UIColor.redColor()
}) { (completed) -> Void in
//animation has completed
//execute your code here
}
Upvotes: 2