Skip to content

Instantly share code, notes, and snippets.

@alexnikol
Created Apr 26, 2020
Embed
What would you like to do?
Example of multiple layer animations
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Creation of View
let square = UIView(frame: CGRect(x: 20, y: 70, width: 370, height: 200))
square.layer.borderColor = UIColor.green.cgColor
square.layer.borderWidth = 2.0
square.layer.cornerRadius = 5
square.backgroundColor = UIColor.systemPink
square.layer.masksToBounds = true
view.addSubview(square)
let globalDuration: CFTimeInterval = 2.0
let globalRepeatCount: Float = 2.0
// MARK: CornerRadius Animation
let cornerAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.cornerRadius))
cornerAnimation.fromValue = 0.0
cornerAnimation.toValue = 20.0
cornerAnimation.duration = globalDuration
cornerAnimation.repeatCount = globalRepeatCount
cornerAnimation.autoreverses = true
// MARK: Position Animation
let positionAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.position))
positionAnimation.fromValue = CGPoint(x: -20, y: 100)
positionAnimation.toValue = CGPoint(x: 280, y: 100)
positionAnimation.duration = globalDuration
positionAnimation.repeatCount = globalRepeatCount
positionAnimation.autoreverses = true
// MARK: Background Animation
let backgroundAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.backgroundColor))
backgroundAnimation.fromValue = UIColor.blue.cgColor
backgroundAnimation.toValue = UIColor.green.cgColor
backgroundAnimation.duration = globalDuration
backgroundAnimation.repeatCount = globalRepeatCount
backgroundAnimation.autoreverses = true
// MARK: Bounds Animation
let boundsAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.bounds))
boundsAnimation.fromValue = CGRect(x: 0, y: 0, width: 20, height: 20)
boundsAnimation.toValue = CGRect(x: 0, y: 0, width: 40, height: 40)
boundsAnimation.duration = globalDuration
boundsAnimation.repeatCount = globalRepeatCount
boundsAnimation.autoreverses = true
// Creation of Sublayer
let newSublayer = CALayer()
newSublayer.frame = CGRect(x: 80, y: 80, width: 40, height: 40)
newSublayer.backgroundColor = UIColor.green.cgColor
newSublayer.layer.addSublayer(newSublayer)
//Apply all animations to sublayer
CATransaction.begin()
newSublayer.add(positionAnimation, forKey: #keyPath(CALayer.position))
newSublayer.add(cornerAnimation, forKey: #keyPath(CALayer.cornerRadius))
newSublayer.add(backgroundAnimation, forKey: #keyPath(CALayer.backgroundColor))
newSublayer.add(boundsAnimation, forKey: #keyPath(CALayer.bounds))
CATransaction.commit()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment