Mbusi Hlatshwayo
Mbusi Hlatshwayo

Reputation: 554

How to animate tableViewCell only once?

I am working on a table view that I want have its cells animated when loaded. I am setting the alpha fade from 0 to 1 over 1.5 seconds. The problem I am running into is that this is animated each time cellForRowAt indexPath is called. Is there a good way to do this so the cell is animated only once and not each time cellForRowAt IndexPath is called? Any help is appreciated. Thanks!

// function to configure custom table view cell 
func configCell(place: Place) {
    // hide image and label before image is loaded
    headlineImage.alpha = 0
    headlineLabel.alpha = 0
    headlineLabel.text = place.name
    // set image asynchronously
    headlineImage.sd_setImage(with: URL(string: "ImageUrl"), placeholderImage: UIImage(named: "restaurant"), options: .continueInBackground) { (_, _, _, _ ) in
            // image download complete fade in image
            print("COMPLETED SD SET IMAGE")
            UIView.animate(withDuration: 1.5, animations: {
                self.headlineImage.alpha = 1
                self.headlineLabel.alpha = 1
            })
    }

}

Upvotes: 0

Views: 526

Answers (1)

Malik
Malik

Reputation: 3802

Something like this might help.

Create a global variable

var isFirstLoad = true

then in your configCell method, wrap the animation inside an if-block and also set the flag to false

func configCell(place: Place) {
    headlineLabel.text = place.name    
    if isFirstLoad == true {
        isFirstLoad = false
        headlineImage.alpha = 0
        headlineLabel.alpha = 0
        headlineImage.sd_setImage(with: URL(string: "ImageUrl"), placeholderImage: UIImage(named: "restaurant"), options: .continueInBackground) { (_, _, _, _ ) in
            print("COMPLETED SD SET IMAGE")
            UIView.animate(withDuration: 1.5, animations: {
                self.headlineImage.alpha = 1
                self.headlineLabel.alpha = 1
            })
        }
    }
}

Upvotes: 1

Related Questions