Swift:两个动画一个接一个

标签 swift swift4 swift4.2

我遇到了这个小动画问题,卡住了。 我想显示两个动画,一个接一个(首先将卡片从按钮刷到中心,然后将其翻转)。 所以我在 UIView.animate 方法中使用完成,在第一个动画完成后触发第二个动画。但在模拟器中,它每次只显示第二个动画。有人可以帮忙吗? 非常感谢

UIView.animate(withDuration: 1, delay: 0, options: .curveEaseOut, animations: {
    let animation:CABasicAnimation = CABasicAnimation(keyPath: "position")
    animation.fromValue = NSValue(cgPoint:CGPoint(x: self.imgBackOfTheCard.frame.midX, y: 1200))
    animation.toValue = NSValue(cgPoint:CGPoint(x: self.imgBackOfTheCard.frame.midX, y: self.imgBackOfTheCard.frame.midY))
    animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
    animation.duration = 1
    self.imgBackOfTheCard.layer.add(animation, forKey: "position")
    }, completion: { (finished: Bool) in
        UIView.animate(withDuration: 1, delay: 1, options: .curveLinear, animations: {
            let transitionOptionsLeft: UIView.AnimationOptions = [.transitionFlipFromLeft, .showHideTransitionViews]
            UIView.transition(from: self.imgBackOfTheCard, to: self.imgFrontCard, duration: 1, options: transitionOptionsLeft, completion: nil)
        })
})

最佳答案

您正在混合 CA 动画和 UIView 动画。

第一个动画是 CABasicAnimationUIView.animate 无法识别它,因此第一个动画立即“完成”(就 UIView.animate 而言)并调用完成闭包。现在你做另一个 UIView 动画。但实际上,第一个动画才刚刚开始,所以第二个动画接管了,您只能看到第二个。

要解决此问题,您应该将第一个动画移出 UIView.animate block :

let animation:CABasicAnimation = CABasicAnimation(keyPath: "position")
animation.fromValue = NSValue(cgPoint:CGPoint(x: self.imgBackOfTheCard.frame.midX, y: 1200))
animation.toValue = NSValue(cgPoint:CGPoint(x: self.imgBackOfTheCard.frame.midX, y: self.imgBackOfTheCard.frame.midY))
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
animation.duration = 1
self.imgBackOfTheCard.layer.add(animation, forKey: "position")

然后等待1秒,再做第二个动画:

DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
   // do your second animation here.
})

经过进一步检查,第一个动画不必是 CABasicAnimation。它也可以用 UIView.animate 创建。只需设置 frame 属性即可。

关于Swift:两个动画一个接一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52576367/

相关文章:

c++ - 在 Swift 中使用 C++ 模板

swift - 在 iOS swift 中将 LAT/Long 转换为位置地址

swift - 将代码更新为 swift 4 的隐式 Objective-C 入口点

ios - Swift 4.2 解包问题 (??)

ios - 更新 cocoapods 库时 pod spec lint 或 pod lib lint 失败

swift - 快速删除字符串中的所有非数字字符

ios - 无法使用 removeFromParent : Swift 删除点击的 spriteNode

ios - Collection View 中的水平滚动

ios - ViewController 中的多个 UICollectionViews |不会调用一个 CollectionViews 委托(delegate)方法