airbnb / lottie-ios

An iOS library to natively render After Effects vector animations
http://airbnb.io/lottie/
Apache License 2.0
25.67k stars 3.74k forks source link

Adding animation to UICollectionViewCell/UITableViewCell #170

Closed petoye closed 7 years ago

petoye commented 7 years ago

I need to know a way to add a LOTAnimationView to a collectionView prototype and then link it to the collectionViewCell. The animation will play when you press a button on the cell. Any ideas?

xinsight commented 7 years ago

You can add an LOTAnimationView to a UICollectionViewCell like any other custom view.

petoye commented 7 years ago

I did try doing that but then I don't know how to exactly play the animation

xinsight commented 7 years ago

Ah, I guess you're using a storyboard. Perhaps someone else can confirm, but It looks like you can't add create LOTAnimationViews from interface builder.

Easiest workaround is to create a UICollectionViewCell subclass, and then add the animation in code. Something like:

import UIKit
import Lottie

class AnimCollectionViewCell: UICollectionViewCell {

    var anim: LOTAnimationView!

    override func awakeFromNib() {
        super.awakeFromNib()

        anim = LOTAnimationView(name: "LottieLogo1")
        anim.contentMode = .scaleAspectFit
        self.contentView.addSubview(anim)

        anim.centerXAnchor.constraint(equalTo: self.contentView.centerXAnchor)
        anim.centerYAnchor.constraint(equalTo: self.contentView.centerYAnchor)

    }

    public func play() {
        anim.play()
    }

}
AmanToshniwal commented 2 years ago

Thank you so much, I was searching all over for this and your solution did wonders.