我有一个UI ImageView,我想旋转180度,占用1秒,然后我想在这个位置等待1秒,然后旋转180度回到原来的位置需要1秒钟. 我该如何做到这一点?我已经尝试了100种方法,它不断向后弹回而不是向后
我该如何做到这一点?我已经尝试了100种方法,它不断向后弹回而不是向后旋转
编辑:我忘了添加我需要这个无限重复
您可以在UIView.animate上显示的completionHandler中执行第二个动画let duration = self.transitionDuration(using: transitionContext) let firstAnimDuration = 0.5 UIView.animate(withDuration: firstAnimDuration, animations: { /* Do here the first animation */ }) { (completed) in let secondAnimDuration = 0.5 UIView.animate(withDuration: secondAnimDuration, animations: { /* Do here the second animation */ }) }
现在你可能有另一个问题.
如果使用CGAffineTransform旋转视图,并且为每个动画分配一个此类型的新对象到view.transform,您将丢失先前的变换操作
所以,根据这篇文章:How to apply multiple transforms in Swift,你需要连接转换操作
2动画块的示例
这是一个旋转180并在1秒后返回原点的例子:
let view = UIView.init(frame: CGRect.init(origin: self.view.center, size: CGSize.init(width: 100, height: 100))) view.backgroundColor = UIColor.red self.view.addSubview(view) var transform = view.transform transform = transform.rotated(by: 180) UIView.animate(withDuration: 2, animations: { view.transform = transform }) { (completed) in transform = CGAffineTransform.identity UIView.animate(withDuration: 2, delay: 1, options: [], animations: { view.transform = transform }, completion: nil) }
.repeat动画和.autoreverse的示例
.animate方法使您能够设置一些动画选项.特别是结构UIViewAnimationOptions包含:
> .repeat,无限重复你的动画块
> .autoreverse,将您的视图恢复到原始状态
考虑到这一点,你可以这样做:
var transform = view.transform.rotated(by: 180) UIView.animate(withDuration: 2, delay: 0, options: [.repeat, .autoreverse], animations: { self.myView.transform = transform })
但是你需要在两个动画之间有一个延迟,所以你需要这样做:
递归动画示例和1秒的延迟
只需在ViewController中创建一个方法,为视图设置动画.在最后一个completionHandler中,只需调用该方法来创建一个无限循环.
最后,您需要在viewDidAppear上调用该方法来启动动画.
override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.animation() } func animation() { var transform = view.transform transform = transform.rotated(by: 180) UIView.animate(withDuration: 2, delay: 0, options: [], animations: { self.myView.transform = transform }) { bool in transform = CGAffineTransform.identity UIView.animate(withDuration: 2, delay: 1, options: [], animations: { self.myView.transform = transform }, completion: { bool in self.animation() }) } }