UICollectionViewCell滚动时缩放单元格大小 [英] UICollectionViewCell scale cell size while scrolling

查看:143
本文介绍了UICollectionViewCell滚动时缩放单元格大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个UICollectionView,当保留"顶部或底部的可见区域时,UICollectionViewCell会按比例缩小.并在进入"可见区域时按比例放大到正常大小.

I'm trying to create a UICollectionView where the UICollectionViewCell is getting scaled down when "leaving" the visible area at the top or bottom. And getting scaled up to normal size while "entering" the visible area.

我一直在尝试一些缩放/动画代码: scrollViewDidScroll(),但似乎无法正确处理.

I've been trying some scale/animation code in: scrollViewDidScroll() , but I can't seem to get it right.

我的完整功能如下:

 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)
            })

        }
    }
}

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

Is this in some way the right approach, or is there another better way?

推荐答案

不是完整的解决方案,但有几点备注/指针:

Not a complete solution, but a few remarks/pointers:

  1. 您不应以这种方式直接弄乱集合视图单元,而应使用自定义的

  1. You should not mess with the collection view cells directly in this way, but rather have a custom UICollectionViewLayout subclass that modifies the UICollectionViewLayoutAttributes to include the desired transform and invalidating the layout whenever necessary.

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

Doing if pos.origin.y == 50 is definitely not a good idea, because the scrolling might not pass by all values (that is, it might jump from 45 to 53). So, use >= and include some other way if you want to ensure that your animation is only executed once at the "boundary" (for example, store the last position or a flag).

这篇关于UICollectionViewCell滚动时缩放单元格大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆