Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swipe Animation for remove Cell in UICollectionView - Swift 2.0

I created an app with UICollectionView like this image:

enter image description here

Added two gestures:

The first (up) will erase the cell.

The second (down) will update the cell (take new data of CoreData). The functions work fine, but there's no animation. iOS has a very cool animation dragging the cell up and the cell disappears.

I am a beginner in animations swift, so I'm a little lost when it.

My question is: How can I add an animation that takes up the entire cell?

I read some answers on the site, but all in Object-C (like this).

Can someone help me?

like image 360
James Avatar asked Oct 23 '15 04:10

James


1 Answers

The best way to achieve the animation on the cell of UICollectionView is overriding its layout UICollectionViewLayout. Its has method which will return the layout attributes of the cell which you want to either appear/insert/delete.

For example: I created a class KDCollectionViewFlowLayout inheriting UICollectionViewFlowLayout and override the delete attribute.

class KDCollectionViewFlowLayout: UICollectionViewFlowLayout {

  override func finalLayoutAttributesForDisappearingItemAtIndexPath(itemIndexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
        let attribute = super.finalLayoutAttributesForDisappearingItemAtIndexPath(itemIndexPath)

        attribute?.transform = CGAffineTransformTranslate(attributes.transform, 0, ITEM_SIZE)
        attribute?.alpha = 0.0
        return attribute

    }
}

Now you need to assign object of this flowLayout to the collection view in either viewDidLoad or you can assign it through storyboard.

let flowLayout = KDCollectionViewFlowLayout()
self.collectionView?.setCollectionViewLayout(flowLayout, animated: true)

Now, you are all set for transformation of cell which you defined in to finalLayoutAttributesForDisappearingItemAtIndexPath method whenever you perform any delete operation on the collectionView.

Update

You need delete the items from collection view using batch operation.

collectionView.performBatchUpdates({ () -> Void in
   //Array of the data which you need to deleted from collection view
    let indexPaths = [NSIndexPath]()
    //Delete those entery from the data base. 

    //TODO: Delete the information from database

    //Now Delete those row from collection View 

    collectionView.deleteItemsAtIndexPaths(indexPaths)

}, completion:nil)
like image 70
deoKasuhal Avatar answered Mar 05 '23 20:03

deoKasuhal