滑动动画以删除UICollectionView中的Cell - Swift 2.0

时间:2015-10-23 04:24:52

标签: swift animation uicollectionview uicollectionviewcell

我创建了一个UICollectionView的应用,就像这张图片一样:

enter image description here

添加了两个手势:

第一个(向上)将擦除单元格。

第二个(向下)将更新单元格(获取CoreData的新数据)。 功能很好,但没有动画。 iOS有一个非常酷的动画拖动单元格,单元格消失。

我很快就是动画的初学者,所以当我有点迷失的时候。

我的问题是:如何添加占据整个单元格的动画?

我在网站上阅读了一些答案,但所有答案都在Object-C(like this)中。

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:13)

UICollectionView单元格上实现动画的最佳方法是覆盖其布局UICollectionViewLayout。它的方法将返回您想要显示/插入/删除的单元格的布局属性。

例如:我创建了一个继承KDCollectionViewFlowLayout的类UICollectionViewFlowLayout并覆盖了删除属性。

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

    }
}

现在您需要将此flowLayout的对象分配给viewDidLoad中的集合视图,或者您可以通过storyboard分配它。

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

现在,只要您对finalLayoutAttributesForDisappearingItemAtIndexPath执行任何删除操作,就可以将您定义的单元格转换为collectionView方法。

<强>更新

您需要使用批处理操作从集合视图中删除项目。

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)