ios - 以编程方式创建的 Animate NSLayoutConstraint

标签 ios swift uiview nslayoutconstraint uiviewanimation

必须做一些特殊的事情才能对以编程方式实例化的约束进行动画处理?

我以编程方式将约束实例化为惰性变量:

private lazy var topConstraint: NSLayoutConstraint = {
    let constraint = view.topAnchor.constraint(equalTo: otherView.topAnchor, constant: otherView)
    return constraint
}()

然后,我以动画方式改变此约束的常量:

topConstraint.constant = newValue
view.setNeedsLayout()
UIView.animate(withDuration: 1) {
    self.view.layoutIfNeeded()
}

它不起作用...我也尝试过将常量设置放入 block 中:

UIView.animate(withDuration: 1) {
    self.topConstraint.constant = newValue
    self.view.setNeedsLayout()
    self.view.layoutIfNeeded()
}

但我一无所获,我几乎尝试了所有的组合。约束常量已正确更改,但始终没有动画。

PD:我还尝试了 UIViewPropertyAnimator

最佳答案

不需要setNeedsLayout()

self.topConstraint.constant = 0.0
UIView.animate(withDuration: 1.0) {[weak self] in
    self?.topConstraint.constant = 10.0 
    self?.view.layoutIfNeeded()
}

关于ios - 以编程方式创建的 Animate NSLayoutConstraint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57868118/

相关文章:

ios - 从深度嵌套的 UIView 快速调用方法

ios - 在另一个应用程序中打开文件时更改 UIDocumentInteractionController 中的文件名

iphone - exc_bad_access 来自实例中的 nsstring - 困难,但很酷

objective-c - 整除后float为0

ios - 通过 Xcode 中的多个 Storyboard segues 传递数据

swift - 如果让 a = b, a.something() 否则

ios - 以编程方式绘制游戏板

c++ - 将 Int32 NAN 转换为 float

ios - 如何显示下面的UIView?

iphone - 如何向一个UIView添加多个UIImageView;从图像列表中