Manuel Peixoto
Manuel Peixoto

Reputation: 372

UICollectionViewController item insert animation Swift

Been trying to animate the item insert on a collection view, the animation is a slide in from outside of the screen from left to right or right to left, for that I'am changing the item's frame origin x value.

enter image description here

My problem is when I call UIView.animate the completion callback is called instantaneously not showing the animation, I've tried to add the animation code inside the item's class, inside the method collectionView(_:cellForItemAt:) and even tried to create a custom viewflowlayout and override the layoutAttributesForItemAtIndexPath to add a transformation, but none of that worked, any suggestions.

Upvotes: 3

Views: 3463

Answers (1)

Rakshith Nandish
Rakshith Nandish

Reputation: 639

This works:

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    UIView.animate(withDuration: 1, animations: {
        var newFrame = cell.frame
        cell.frame = CGRect(x: newFrame.origin.x + 50, y: newFrame.origin.y, width: newFrame.width, height: newFrame.height)
    })
}

Replace the offset as per your need.

Also this works too:

cell.frame.origin.x = cell.frame.origin.x + 50

inside of the willDisplayCell

Upvotes: 6

Related Questions