我有一个UITextField,我想在点击时放大它的宽度 . 我设置了约束,并确保左边的约束优先级低于我试图在右边设置动画的约束 .
这是我尝试使用的代码 .
// move the input box
UIView.animateWithDuration(10.5, animations: {
self.nameInputConstraint.constant = 8
}, completion: {
(value: Bool) in
println(">>> move const")
})
这有效,但它似乎只是瞬间发生,似乎没有任何动作 . 我试着设置它10秒钟以确保我没有遗漏任何东西,但我得到了相同的结果 .
nameInputConstraint是我控制拖动以从IB连接到我的类的约束的名称 .
感谢您的帮助!
6 回答
您需要先更改约束,然后为更新设置动画 .
在Swift 3.0中:
SWIFT 4.x :
完成示例:
使用Swift 4.1和iOS 11,根据您的需要,您可以选择以下3种方法之一来解决您的问题 .
#1 . 使用UIView的animate(withDuration:animations :)类方法
animate(withDuration:animations:)有以下声明:
下面的Playground代码显示了
animate(withDuration:animations:)
的可能实现,以便为Auto Layout约束的常量更改设置动画 .#2 . 使用UIViewPropertyAnimator的init(duration:curve:animations :) initialiser和startAnimation()方法
init(duration:curve:animations:)有以下声明:
下面的Playground代码显示了
init(duration:curve:animations:)
和startAnimation()
的可能实现,以便为Auto Layout约束的常量更改设置动画 .#3 . 使用UIViewPropertyAnimator的runningPropertyAnimator(withDuration:delay:options:animations:completion :)类方法
runningPropertyAnimator(withDuration:delay:options:animations:completion:)有以下声明:
下面的Playground代码显示了
runningPropertyAnimator(withDuration:delay:options:animations:completion:)
的可能实现,以便为Auto Layout约束的常量更改设置动画 .指出
view.layoutIfNeeded()
仅适用于视图子视图非常重要 .因此,要为视图约束设置动画,必须在视图到动画 superview 上调用它,如下所示:
简单布局的示例如下:
就我而言,我只更新了自定义视图 .
观看this .
视频说您需要添加
self.view.layoutIfNeeded()
,如下所示: