同时在不同对象上进行多个动画并最终完成

Multiple animations on different objects at the same time with a final completion

基本上,我有一个 UITableView 我想在点击按钮时设置动画的地方。每个单元格都应该按 1.10 和 return 缩放到它们的变换身份。所以我用 UIView.animateKeyframesWithDuration.

为每个单元格制作了两种不同的动画

但我想让它们稍微延迟一下。所以我在这样的循环中调用这个方法:

for (index, cell) in tableView.visibleCells.enumerate() {
    let delay = 0.1 * Double(index)

    let duration = 0.5

    UIView.animateKeyframesWithDuration(duration, delay: delay, options: [], animations: {
        UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: duration * 1/2, animations: {
            cell.transform = CGAffineTransformScale(cell.transform, 1.10, 1.10)
        })
        UIView.addKeyframeWithRelativeStartTime(1/2, relativeDuration: duration * 1/2, animations: {
            cell.transform = CGAffineTransformIdentity
        })
        }, completion: nil)
}

问题是完成部分仅适用于每个动画。

我正在寻找一种在每个动画完成后做某事的方法。我怎样才能做到这一点?

您可以将所有内容包装在一个 UIView.animateKeyframesWithDuration 调用中,并像这样调用一个完成块:

let delay = 0.1
let duration = 0.5
let totalDuration = duration + TimeInterval(tableView.visibleCells.count - 1) * delay

UIView.animateKeyframes(
    withDuration: totalDuration/2,
    delay: 0,
    options: [],
    animations: {
        for (index, cell) in self.tableView.visibleCells.enumerated() {
            let relativeDelay = delay * Double(index)

            print("Cell \(index) animation starts after relative delay: \(relativeDelay)")

            UIView.addKeyframe(withRelativeStartTime: relativeDelay, relativeDuration: duration/2, animations: {
                cell.transform = cell.transform.scaledBy(x: 1.10, y: 1.10)
            })
            UIView.addKeyframe(withRelativeStartTime: relativeDelay +  duration/2, relativeDuration: duration/2, animations: {
                cell.transform = CGAffineTransform.identity
            })
        }
}, completion: { finished in
    if finished {
        print("Done")
    }
})

希望这就是你想要的。