UICollectionViewCell在滚动时更改单元格大小 [英] UICollectionViewCell change cell size while scrolling
问题描述
我正在尝试创建一个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.
我的完整函数如下所示:
My complete function looks like this:
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:
-
你不应该以这种方式直接搞乱集合视图单元格,而是要有一个自定义
UICollectionViewLayout
子类修改UICollectionViewLayoutAttributes
包含所需的转换
并在必要时使布局无效。
You should not mess with the collection view cells directly in this way, but rather have a custom
UICollectionViewLayout
subclass that modifies theUICollectionViewLayoutAttributes
to include the desiredtransform
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屋!