等待Swift动画完成,然后再执行代码
我正在尝试为UIImageView设置动画,然后在动画完成后隐藏图像视图。但是,在动画完成之前imageview被隐藏了。我看过类似的问题,他们建议在完成后在动画代码中实现动画侦听器或执行.hidden代码,但是我不确定如何在下面的shockView()函数中影响此效果。
仅在动画完成后,如何显示摇动动画并隐藏图像视图?
使用以下代码调用动画:
shakeView(image1!)shakeView(image2)
image1!.hidden = true
image2.hidden = true
动画功能本身如下所示:
func shakeView(iv: UIImageView){ var shake:CABasicAnimation = CABasicAnimation(keyPath: "position")
shake.duration = 0.1
shake.repeatCount = 2
shake.autoreverses = true
var from_point:CGPoint = CGPointMake(iv.center.x - 5, iv.center.y)
var from_value:NSValue = NSValue(CGPoint: from_point)
var to_point:CGPoint = CGPointMake(iv.center.x + 5, iv.center.y)
var to_value:NSValue = NSValue(CGPoint: to_point)
shake.fromValue = from_value
shake.toValue = to_value
iv.layer.addAnimation(shake, forKey: "position")
}
回答:
CATransaction
动画完成后,您可以使用来调用完成块。
func shakeView(iv: UIImageView){ CATransaction.begin()
CATransaction.setCompletionBlock({
iv.hidden = true
})
var shake:CABasicAnimation = CABasicAnimation(keyPath: "position")
shake.duration = 0.1
shake.repeatCount = 21
shake.autoreverses = true
var from_point:CGPoint = CGPointMake(iv.center.x - 5, iv.center.y)
var from_value:NSValue = NSValue(CGPoint: from_point)
var to_point:CGPoint = CGPointMake(iv.center.x + 5, iv.center.y)
var to_value:NSValue = NSValue(CGPoint: to_point)
shake.fromValue = from_value
shake.toValue = to_value
iv.layer.addAnimation(shake, forKey: "position")
CATransaction.commit()
}
或者,您也可以将两个动画组合在一起,CATransaction
如下所示。
func shakeView(iv: UIImageView){ var shake:CABasicAnimation = CABasicAnimation(keyPath: "position")
shake.duration = 0.1
shake.repeatCount = 21
shake.autoreverses = true
var from_point:CGPoint = CGPointMake(iv.center.x - 5, iv.center.y)
var from_value:NSValue = NSValue(CGPoint: from_point)
var to_point:CGPoint = CGPointMake(iv.center.x + 5, iv.center.y)
var to_value:NSValue = NSValue(CGPoint: to_point)
shake.fromValue = from_value
shake.toValue = to_value
iv.layer.addAnimation(shake, forKey: "position")
}
override func viewDidLoad() {
CATransaction.begin()
CATransaction.setCompletionBlock({
self.image1.hidden = true
self.image2.hidden = true
})
shakeView(image1)
shakeView(image)
CATransaction.commit()
}
以上是 等待Swift动画完成,然后再执行代码 的全部内容, 来源链接: utcz.com/qa/423702.html