Last active
January 28, 2019 09:23
-
-
Save markohlebar/674fd9c166527723fa031063d03099e3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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