我正在尝试为框架中UICollectionView
visibile的每个单元设置动画。
每次滚动时,都会出现一个带有动画的新单元格。
我在performBatchUpdates
内使用cellForItemAtIndexPath
执行此操作但是,动画同时应用于所有单元格且非常快。似乎1秒的动画无法识别。
此外,我试图找到按下按钮时将动画应用到单元格的方法,但没有成功。
我使用的代码是:
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
let Cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! CellClass
self.collectionView?.performBatchUpdates({
Cell.layer.cornerRadius = 200
return
}){
completed in
UIView.animateWithDuration(1, animations: {
Cell.layer.cornerRadius = 0
})
}
Cell.playAnimationBtn.layer.setValue(indexPath.row, forKey: "indexPlayBtn")
}
@IBAction func actionGetAnimation(sender: UIButton)
{
let indexUser = (sender.layer.valueForKey("indexPlayBtn")) as! Int
//Cell selected do animation corners = 200
}
答案 0 :(得分:3)
将动画移动到willDisplayCell(_:cell:indexPath:)
时,可以使其工作。每次要显示新单元格时都会调用该方法。
您不能将UIView.animateWithDuration
用于图层属性。您必须使用CABasicAnimation
。
如果您想在用户按下按钮时为单元设置动画,可以从下面的代码示例中调用animateCellAtIndexPath
。您必须知道单元格的indexPath才能这样做。在此示例中,我在用户选择单元格时调用此方法。
func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
animateCell(cell)
}
func animateCell(cell: UICollectionViewCell) {
let animation = CABasicAnimation(keyPath: "cornerRadius")
animation.fromValue = 200
cell.layer.cornerRadius = 0
animation.toValue = 0
animation.duration = 1
cell.layer.addAnimation(animation, forKey: animation.keyPath)
}
func animateCellAtIndexPath(indexPath: NSIndexPath) {
guard let cell = collectionView.cellForItemAtIndexPath(indexPath) else { return }
animateCell(cell)
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
animateCellAtIndexPath(indexPath)
}