在UICollectionView中实现滑动删除单元格的动画 - Swift 2.0

8

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

enter image description here

添加了两个手势:

第一个手势(向上)将抹掉该单元格。

第二个手势(向下)将更新该单元格(获取CoreData的新数据)。这些功能都很好用,但没有动画。iOS有一个非常酷的动画,将单元格拖到上面,单元格消失。

我是一个初学者,在swift动画方面有点迷茫。

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

我在网站上阅读了一些答案,但全部都是Object-C写的(像这样)。

有人能帮帮我吗?


詹姆斯,你的应用看起来很棒! - Cody Weaver
詹姆斯,你最终实现了你想要的功能吗?我正在寻找在Swift中完全相同类型的功能。如果你的应用程序也能正常工作,我很想看看它! - David West
1个回答

14

实现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

    }
}
您需要在viewDidLoad中或通过storyboard将此flowLayout对象分配给集合视图。
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)

首先,我尝试将我的代码整合进去,但没有成功。我的代码分为三部分:一个类和两个扩展。链接我该如何将他的示例代码融入到我的代码中?现在比一开始更加困惑了... - James
不好意思,我在这里没有工作过,你能否提供一个下载链接给我,让我实际看一下你是如何组织所有内容的? - James
@James,这是一个完美的示例代码,用于删除动画。 - deoKasuhal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接