Iram Fattah
Iram Fattah

Reputation: 1

Changing UI elements in a custom CollectionViewCell using didSelect method

I'm working on a simple flashcard app. The cards are loaded into a collection view. When someone clicks on the card I want a rotation animation to occur and the text label to change to the answer.

func animateRotationY(view: UIImageView) {
    let animation = CABasicAnimation(keyPath: "transform.rotation.y")
    let angleRadian = CGFloat.pi * 2
    animation.fromValue = 0
    animation.byValue = angleRadian
    animation.toValue = angleRadian
    animation.duration = 1.0
    animation.repeatCount = 1
    view.layer.add(animation, forKey: nil)

}

Im calling this animation function in the didSelect method as such

extension FlashCardsViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        let cell = flashCardsView.collectionView.dequeueReusableCell(withReuseIdentifier: "FlashCardCell", for: indexPath) as! FlashCardCollectionViewCell

        let row = indexPath.row
        let selectedCard = flashCards[row]
        animateRotationY(view: cell.imageView)
    selectedIndexPath = row
        cell.textLabel.text = selectedCard.answer
    self.flashCardsView.collectionView.reloadData()

}

Problem is, not only will the animation not show, but the textLabel wont even update even though the breakpoints are hitting those lines. Does anyone have any idea how I can update UI in the didSelect?

Upvotes: 0

Views: 49

Answers (1)

Cezar
Cezar

Reputation: 56372

When you call dequeueReusableCell(withReuseIdentifier:for:), you're not getting the cell that is already shown and you want to change.

You should call flashCardsView.collectionView.cellForItem(at: indexPath) instead.

Also, calling reloadData() is causing collectionView(_:cellForItemAt:) to be called for every index path, which might be overriding whatever changes you made after selecting the cell.

Upvotes: 1

Related Questions