我创建了一个自定义的 UICollectionViewCell
,它包含一个名为 animView
的 subview ,我打算将其设置为动画。 animView
的形状是一个规则的垂直矩形。
在 configureCell()
方法中,我使用下面的代码配置单元格并创建动画,但我没有看到动画。
animView.transform = CGAffineTransform(scaleX: 1.0, y: 0.5)
self.layoutIfNeeded()
UIView.animate(withDuration: 0.7, delay: 0, options: [.curveEaseOut], animations: {
self.animView.transform = CGAffineTransform.identity
self.layoutIfNeeded()
}, completion: nil)
但是,当我尝试为整个单元格设置动画时,我看到单元格成功设置了动画。
self.transform = CGAffineTransform(scaleX: 1.0, y: 0.5)
self.layoutIfNeeded()
UIView.animate(withDuration: 0.7, delay: 0, options: [.curveEaseOut], animations: {
self.transform = CGAffineTransform.identity
self.layoutIfNeeded()
}, completion: nil)
非常感谢您抽出时间来回答。
编辑:
根据建议,我更改了调用动画的位置,如下所示。现在,当我尝试为整个单元制作动画时,它正在工作。但是,我想为 animView 设置动画,它是自定义 UICollectionViewCell (BarCell) 的 subview 。但它不是动画。有什么想法吗?
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
let cells = collectionView.visibleCells
for cell in cells {
let current = cell as! BarCell
let curAnimView = current.animView
curAnimView?.transform = CGAffineTransform(translationX: 0, y: current.animFillHeightCons.constant)
UIView.animate(withDuration: 0.7) {
curAnimView?.transform = CGAffineTransform.identity
}
}
}
最佳答案
您只需要为可见单元格启动动画。 以下是您可以如何做到这一点。
添加这个
UIScrollViewDelegate
它将提供方法
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let cells = colAnim.visibleCells
for cell in cells
{
let current = cell as! testCollectionViewCell
UIView.animate(withDuration: 2.0, animations: {
current.animView.transform = CGAffineTransform(translationX: -400, y: 0)
//Change this animation
})
}
}
还要确保也这样做。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "testCollectionViewCell", for: indexPath) as! testCollectionViewCell
cell.animView.transform = CGAffineTransform(translationX: 0, y: 0)// This one
return cell
}
通过这样做,您可以仅在单元格可见时实现动画。 谢谢。
关于ios - 如何在 UICollectionViewCell 中为 UIView 设置动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48131016/