同时运行两个动画

时间:2018-01-18 16:00:04

标签: ios swift uiviewanimation

我正在尝试使用两个视图创建动画,并且在执行时遇到了一些意外行为。

我想在制作第二个动画transitionFlipFromBottom

时为两个视图位置设置动画

以下是代码:

let initialFrame = CGRect(x: xpos, y: -310, width: 300, height: 300)

let firstView = UIView()
firstView.backgroundColor = .red
firstView.frame = initialFrame

let secondView = UIView()
secondView.backgroundColor = .white
secondView.frame = initialFrame
secondView.isHidden = false


self.view.addSubview(firstView)
self.view.addSubview(secondView)


// Here I try to move the views on screen while fliping them
UIView.animate(withDuration: 1, delay: 0, options: .curveEaseOut, animations: {
    secondView.center = self.view.center
    firstView.center = self.view.center
    self.flip(firstView: firstView, secondView: secondView)
}, completion: nil)



// This function flips the views vertically while it animates the transition from the first to the second view
fileprivate func flip(firstView: UIView, secondView: UIView) {
    let transitionOptions: UIViewAnimationOptions = [.transitionFlipFromBottom, .showHideTransitionViews]
    UIView.transition(with: firstView, duration: 0.5, options: transitionOptions, animations: {
        firstView.isHidden = true
    })

    UIView.transition(with: secondView, duration: 0.5, options: transitionOptions, animations: {
        secondView.isHidden = false
    })
}

上面的代码无法同时执行这两个动画。

只有在第一个动画(移动框架)完成后,在flip块内放置completion函数调用时,它才有效,如下所示:

UIView.animate(withDuration: 1, delay: 0, options: .curveEaseOut, animations: {
    secondView.center = self.view.center
    firstView.center = self.view.center
}, completion: {(_) in
    self.flip(firstView: dummyView, secondView: newGroupView)
})

我甚至尝试使用UIView.animateKeyframes,但它仍无效。

我在这里遗漏了什么吗?

谢谢。

1 个答案:

答案 0 :(得分:2)

有几件事:

  1. transition中,指定.allowAnimatedContent选项。

  2. 推迟动画:

    DispatchQueue.main.async {
        UIView.animate(withDuration: 1, delay: 0, options: [.curveEaseOut], animations: {
            secondView.center = CGPoint(x: self.view.bounds.midX, y: self.view.bounds.midY)
            firstView.center = CGPoint(x: self.view.bounds.midX, y: self.view.bounds.midY)
            self.flip(firstView: firstView, secondView: secondView)
        }, completion: { _ in
        })
    }
    
  3. 有些不相关,你不想要:

    secondView.center = self.view.center
    

    相反,请执行:

    secondView.center = CGPoint(x: self.view.bounds.midX, y: self.view.bounds.midY)
    

    您想在secondView.center的{​​{1}}的坐标空间中设置bounds,而不是view的{​​{1}}。

    < / LI>