Skip to content

Instantly share code, notes, and snippets.

@markohlebar
Last active January 28, 2019 09:23
Show Gist options
  • Save markohlebar/674fd9c166527723fa031063d03099e3 to your computer and use it in GitHub Desktop.
Save markohlebar/674fd9c166527723fa031063d03099e3 to your computer and use it in GitHub Desktop.
import UIKit
import Lottie
/// This class deals with the problems of updating animation frame with Lottie
/// as described here https://github.com/airbnb/lottie-ios/issues/763
class AnimationView: UIView {
private var previousSize: CGSize?
private var frameUpdateDisplayLink: CADisplayLink?
private var animationView: LOTAnimationView! = nil
required init?(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
func play(fromProgress: CGFloat = 0.0,
toProgress: CGFloat = 1.0,
withCompletion completion:LOTAnimationCompletionBlock? = nil ) {
animationView.play(fromProgress: fromProgress,
toProgress: toProgress,
withCompletion: completion)
}
override var bounds: CGRect {
didSet {
startFrameUpdateLink()
}
}
func setAnimation(named animationName:String) {
animationView.setAnimation(named: animationName)
}
deinit {
stopFrameUpdateLink()
}
}
private extension AnimationView {
func commonInit() {
animationView = LOTAnimationView(frame: self.bounds)
addSubview(animationView)
}
func startFrameUpdateLink() {
stopFrameUpdateLink()
frameUpdateDisplayLink = CADisplayLink(target: self, selector: #selector(update))
frameUpdateDisplayLink?.add(to: .current, forMode: .common)
}
func stopFrameUpdateLink() {
frameUpdateDisplayLink?.invalidate()
frameUpdateDisplayLink = nil
previousSize = nil
}
@objc func update() {
guard let size = self.layer.presentation()?.frame.size else {
return
}
animationView.frame = CGRect(origin: .zero, size: size)
if size == previousSize {
stopFrameUpdateLink()
}
previousSize = size
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment