xcode 使用 Swift 4 和 UIView 的奇怪动画行为
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46460356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Weird animation behavior using Swift 4 and UIView
提问by user3582537
I really can't figure out what's wrong with my code. Let me explain in detail what was my aim:
我真的无法弄清楚我的代码有什么问题。让我详细解释一下我的目标是什么:
- I have two
UIView
in the sameUIViewController
. They're called "redSquare
" and "greenSquare
". - When the
UIViewController
is presented I want to animate theredSquare
in order to move on the Y-axis till it reaches the top-border of thegreenSquare
.
- 我有两个
UIView
在同一个UIViewController
。它们被称为“redSquare
”和“greenSquare
”。 - 当
UIViewController
出现时,我想为 设置动画redSquare
以便在 Y 轴上移动,直到它到达greenSquare
.
This is how I set the xCode project:
这就是我设置 xCode 项目的方式:
The behavior that I got is completely the opposite and I really can't understand why and what's happening:
我得到的行为完全相反,我真的无法理解为什么以及发生了什么:
Any tips or explanations for this?
对此有什么提示或解释吗?
回答by Michael Dautermann
Okay. Part of the problem is that you're aligning the center Y... which means that you're trying to break constraints with your animation.
好的。部分问题是您正在对齐中心 Y...这意味着您试图打破动画的约束。
Another part of the problem is that you are doing your animation in viewDidLoad
, which totally runs before viewWillAppear
and viewDidAppear
get called.
问题的另一部分是您在 中制作动画viewDidLoad
,它完全运行在之前viewWillAppear
并被viewDidAppear
调用。
For my own animations, I usually animate a constraint.
对于我自己的动画,我通常为一个约束设置动画。
That is, get rid of the center-Y constraint for your red box and add a new constraint putting the red box some Y distance from the bottom of the superview. Connect this new constraint to an outlet and then you can animate like this:
也就是说,去掉红框的 center-Y 约束,并添加一个新的约束,使红框离超级视图底部有一些 Y 距离。将此新约束连接到插座,然后您可以像这样制作动画:
@IBOutlet weak var redYConstraint : NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// This line sets the red box to be in the center Y of the green box
self.redYConstraint.constant = self.greenSquare.frame.midY
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
UIView.animate(withDuration: 3.0, delay: 2.0, options: UIViewAnimationOptions.curveEaseIn, animations: {
self.redYConstraint.constant = self.greenSquare.frame.maxY
self.view.layoutIfNeeded()
}, completion: nil)
}