UICollectionViewCell在滚动时更改单元格大小

Kva*_*ken 6 scroll ios uicollectionview uicollectionviewcell swift

我正在尝试创建一个UICollectionView,当"离开"顶部或底部的可见区域时,UICollectionViewCell会缩小.并且在"进入"可见区域时扩大到正常尺寸.

我一直在尝试一些比例/动画代码: scrollViewDidScroll() ,但我似乎无法做到正确.

我的完整功能如下所示:

 func scrollViewDidScroll(scrollView: UIScrollView) {

    var arr = colView.indexPathsForVisibleItems()

    for indexPath in arr{

        var cell = colView.cellForItemAtIndexPath(indexPath as! NSIndexPath)!
        var pos = colView.convertRect(cell.frame, toView: self.view)

        if pos.origin.y < 50 && pos.origin.y >= 0{

            cell.hidden = false

            UIView.animateWithDuration(0.5, animations: { () -> Void in

                cell.transform = CGAffineTransformMakeScale(0.02 * pos.origin.y, 0.02 * pos.origin.y)

            })

        }else if pos.origin.y == 50{

            UIView.animateWithDuration(0.5, animations: { () -> Void in

                cell.transform = CGAffineTransformMakeScale(1, 1)
            })

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这在某种程度上是正确的方法,还是有另一种更好的方法?

Dan*_*ser 5

不是一个完整的解决方案,而是一些评论/指针:

  1. 您不应该以这种方式直接混淆集合视图单元格,而是要有一个自定义UICollectionViewLayout子类,修改它UICollectionViewLayoutAttributes以包含所需的transform并在必要时使布局无效.

  2. if pos.origin.y == 50绝对不是一个好主意,因为滚动可能不会通过所有值(也就是说,它可能会从45跳到53).因此,>=如果要确保动画仅在"边界"执行一次(例如,存储最后一个位置或标志),请使用并包含其他一些方法.