【问题标题】:Swift UIView frame not properly updating within animateWithDurationSwift UIView 框架未在 animateWithDuration 内正确更新
【发布时间】:2015-08-31 15:19:02
【问题描述】:

我正在尝试使用animateWithDuration 更新UIView 的位置。当动画开始出现时,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 位置没有在代码中正确设置?

【问题讨论】:

    标签: ios swift uiview nslayoutconstraint animatewithduration


    【解决方案1】:

    如果您尝试使用约束进行动画处理,则应改为更改约束,然后在父视图的动画块中调用 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()
        })
    }
    

    【讨论】:

    • 谢谢。我不知道你必须在动画块之外设置约束。
    猜你喜欢
    • 2015-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-24
    • 1970-01-01
    • 2021-09-23
    • 2016-06-03
    相关资源
    最近更新 更多