Iva*_*ino 5 uiviewanimation ios swift
我正在尝试使用两个视图创建动画,但在执行它们时遇到了一些意外行为。
我想在做第二个动画时为两个视图位置设置动画 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
})
}
Run Code Online (Sandbox Code Playgroud)
上面的代码无法同时执行两个动画。
只有在第一个动画(移动帧)完成后,我将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)
})
Run Code Online (Sandbox Code Playgroud)
我什至尝试使用,UIView.animateKeyframes但它仍然不起作用。
我在这里错过了什么吗?
谢谢你。
有几件事:
在 中transition,指定.allowAnimatedContent选项。
推迟动画:
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
})
}
Run Code Online (Sandbox Code Playgroud)有点不相关,你不想要:
secondView.center = self.view.center
Run Code Online (Sandbox Code Playgroud)
相反,请执行以下操作:
secondView.center = CGPoint(x: self.view.bounds.midX, y: self.view.bounds.midY)
Run Code Online (Sandbox Code Playgroud)
您想要在ofsecondView.center的坐标空间中设置,而不是在s中。boundsviewviewsuperview