【问题标题】:Updating constraints in animation with Swift使用 Swift 更新动画中的约束
【发布时间】:2015-06-04 08:13:19
【问题描述】:

我想要一个动画将 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

标签: ios swift autolayout constraints


【解决方案1】:

您需要更新约束并为 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: {})

【讨论】:

  • 我试过这样做,不幸的是它不起作用:-/
  • 约束是否在没有动画的情况下移动?
  • 不,不是,但我发现了我的错误(请参阅问题中的更新):-)
【解决方案2】:

所以我发现它的错误是一个非常简单的错误。我没有调用self.view.setTranslatesAutoresizingMaskIntoConstraints(false),因为我认为故事板已经处理了(因为我在其中使用了自动布局)。我只是在更新约束之前添加了它。 感谢所有输入:-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 1970-01-01
    相关资源
    最近更新 更多