Swift UIView框架在animateWithDuration

时间:2015-08-31 15:19:02

标签: ios swift uiview nslayoutconstraint animatewithduration

我尝试使用UIView更新animateWithDuration的位置。当动画开始发生时,UIView开始更新,但随后完成使其跳转到正确的位置。这告诉我UIView框架的设置没有正确设置,但我没有看到原因。这是代码:

func showInfoView() {

    infoView.hidden = false
    let newPosition = self.view.frame.height - (self.infoView.frame.height + 260)

    UIView.animateWithDuration(2.0, animations: {
        // Set the view to have the new y position
        self.infoView.frame.origin.y = newPosition
        }, completion: { finished in

            // Remove previous constraint
            if (self.hintConstraint != nil) {
                self.view.removeConstraint(self.hintConstraint)
            }

            // Create the new constraint
            self.hintConstraint = NSLayoutConstraint(item: self.infoView, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1, constant: newPosition)
            self.view.addConstraint(self.hintConstraint)
    })
}

有人能帮助我理解为什么y位置没有在代码中正确设置吗?

1 个答案:

答案 0 :(得分:2)

如果您尝试使用约束设置动画,则应改为更改约束,然后在父视图的动画块中调用layoutIfNeeded

1)在动画块之外设置新约束

2)在动画块中,在父视图上调用layoutIfNeeded

func showInfoView() {

    infoView.hidden = false
    let newPosition = self.view.frame.height - (self.infoView.frame.height + 260)
    self.hintConstraint = NSLayoutConstraint(item: self.infoView, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1, constant: newPosition)

    UIView.animateWithDuration(2.0, animations: {
        self.view.layoutIfNeeded()
    })
}