如何仅为一个 indexPath.row 项目在 CollectionView 单元格中设置动画?

Posted

技术标签:

【中文标题】如何仅为一个 indexPath.row 项目在 CollectionView 单元格中设置动画?【英文标题】:How to set animation in CollectionView cell only for one indexPath.row item? 【发布时间】:2015-11-19 14:52:14 【问题描述】:

我有 UICollectionView,我只想为一个单元格启动图像动画。但问题是,当我添加此动画时,会影响多个项目而不是一个单元格。 代码如下:

func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int

    return 1


func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int

    return arrays.count


func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell

    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as! CollectionViewCell

    if (indexPath.row == 0)
    
        //do the animation

【问题讨论】:

【参考方案1】:

问题是细胞正在被重复使用。这样想,如果你有 100 个不同的对象,但一次只显示 2 个,collectionview 只会创建,比如说,大约 4 个单元格。这样做是为了节省内存并提高性能

因此,如果屏幕上的单元格 A 和 B 分别显示来自数组 [0] 和数组 [1] 的详细信息,然后开始滚动,接下来出现的单元格将是显示数组 [2] 的 C 和 D 和数组[3]。但是,如果您继续滚动,A 和 B 将再次出现,但这次它会显示数组 [4] 和数组 [5] 的信息。然后,如果您继续滚动,它将再次显示单元格 C 和 D,但包含数组 [6] 和数组 [7] 的信息。这就是细胞复用的思路

因此,在您的情况下,您正在将动画应用到单元格 A,但是当您滚动时,您会一直在“其他单元格”上看到此动画。这些其他单元格实际上是单元格 A 被重复使用。

解决方案是让您在调用 cellForItemAtIndexPath: 时停止单元格上的动画,即

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell

    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as! CollectionViewCell
    /* 
    Stop animation in case the cell is already being animated
    */
    if (indexPath.row == 0)
    
        //do the animation

【讨论】:

以上是关于如何仅为一个 indexPath.row 项目在 CollectionView 单元格中设置动画?的主要内容,如果未能解决你的问题,请参考以下文章

如何“重置”下一个 indexPath.row 成为当前 indexPath.row?

如何在 UITableView 中获取选定的 indexPath.section 和 indexPath.row 值?

如何获取当前正在显示的tableView的indexPath.row?

如何在Objective C中的didFinishLoading中获取IndexPath.row

如果超过 indexpath.row,如何在表格视图中设置单元格行高?

如何从扩展的 collectionview 到达 tableview 的 indexpath.row?