Swift 2 – performBatchUpdates – 在UICollectionView框架内部可视化的时候,一个接一个地animation单元格

我试图在框架中animation我的UICollectionView visibile的每个单元格。 每当我滚动一个新的细胞与animation出现。

我正在使用cellForItemAtIndexPath内的performBatchUpdates ,但是,animation是同时应用到所有单元格,它的速度非常快。 看来,1秒的animation不被识别。

另外,我试图find一种方法来应用animation的单元格时,按下button没有成功。

我使用的代码是:

 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 } 

将animation移动到willDisplayCell(_:cell:indexPath:)时,可以使其工作。 每当新的单元即将被显示时,该方法被调用。

您不能使用UIView.animateWithDuration图层属性。 你必须使用CABasicAnimation

如果您想在用户按下button时为单元格设置animation,则可以从下面的代码示例中调用animateCellAtIndexPath 。 你必须知道单元格的indexPath才能这样做。 在这个例子中,当用户select单元格时,我调用这个方法。

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