UICollectionViewCell 滚动时缩放单元格大小 [英] UICollectionViewCell scale 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
包含所需的transform
并在必要时使布局无效.
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.
做 if pos.origin.y == 50
绝对不是一个好主意,因为滚动可能不会通过所有值(即它可能会从 45 跳到 53).因此,如果您想确保动画只在边界"处执行一次(例如,存储最后一个位置或标志),请使用 >=
并包含其他方式.p>
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屋!