使用 Swift 更新动画中的约束
Updating constraints in animation with Swift
我想要一个动画将 UIImageView 移动到由一组新约束定义的新位置,但由于某种原因我无法让它工作。我正在尝试做:
@IBOutlet weak var oldBottom: NSLayoutConstraint!
...
func animateMovement() {
// Here I'm defining a new constraint
var newBottom = NSLayoutConstraint(
item: self.logo,
attribute: NSLayoutAttribute.Bottom,
relatedBy: NSLayoutRelation.Equal,
toItem: self.usernameField,
attribute: NSLayoutAttribute.Bottom,
multiplier: 1,
constant: 15)
self.view.layoutIfNeeded()
UIView.animateWithDuration(1.0, animations: {
// Here I'm setting the already existing constraint (defined in storyboard) to the new constraint
self.oldBottom = newBottom
self.view.layoutIfNeeded()
}, completion: {})
}
您需要更新约束并为 layoutIfNeeded 设置动画,试试这个:
func animateMovement() {
var newBottom = NSLayoutConstraint(
item: self.logo,
attribute: NSLayoutAttribute.Bottom,
relatedBy: NSLayoutRelation.Equal,
toItem: self.usernameField,
attribute: NSLayoutAttribute.Bottom,
multiplier: 1,
constant: 15)
self.view.layoutIfNeeded()
self.oldBottom = newBottom
UIView.animateWithDuration(1.0, animations: {
self.view.layoutIfNeeded()
}, completion: {})
所以我发现错误是一个非常简单的错误。我没有 callself.view.setTranslatesAutoresizingMaskIntoConstraints(false) 因为我认为情节提要已经处理了(因为我在其中使用了自动布局)。我只是在更新约束之前添加了它。
感谢所有的输入:-)
我想要一个动画将 UIImageView 移动到由一组新约束定义的新位置,但由于某种原因我无法让它工作。我正在尝试做:
@IBOutlet weak var oldBottom: NSLayoutConstraint!
...
func animateMovement() {
// Here I'm defining a new constraint
var newBottom = NSLayoutConstraint(
item: self.logo,
attribute: NSLayoutAttribute.Bottom,
relatedBy: NSLayoutRelation.Equal,
toItem: self.usernameField,
attribute: NSLayoutAttribute.Bottom,
multiplier: 1,
constant: 15)
self.view.layoutIfNeeded()
UIView.animateWithDuration(1.0, animations: {
// Here I'm setting the already existing constraint (defined in storyboard) to the new constraint
self.oldBottom = newBottom
self.view.layoutIfNeeded()
}, completion: {})
}
您需要更新约束并为 layoutIfNeeded 设置动画,试试这个:
func animateMovement() {
var newBottom = NSLayoutConstraint(
item: self.logo,
attribute: NSLayoutAttribute.Bottom,
relatedBy: NSLayoutRelation.Equal,
toItem: self.usernameField,
attribute: NSLayoutAttribute.Bottom,
multiplier: 1,
constant: 15)
self.view.layoutIfNeeded()
self.oldBottom = newBottom
UIView.animateWithDuration(1.0, animations: {
self.view.layoutIfNeeded()
}, completion: {})
所以我发现错误是一个非常简单的错误。我没有 callself.view.setTranslatesAutoresizingMaskIntoConstraints(false) 因为我认为情节提要已经处理了(因为我在其中使用了自动布局)。我只是在更新约束之前添加了它。 感谢所有的输入:-)