UIView 动画不适用于 NSLayoutConstraint?

UIView Animation not working with NSLayoutConstraint?

我有一个键盘通知,我想要它,以便在它关闭时,占位符视图以动画形式移动到搜索栏的左边缘。

下面是我调用的与键盘打开异步的动画。目前,视图移动到我想要的位置,但它就像传送到那里而不是动画。

        DispatchQueue.main.async {
            if isKeyboardShowing {
                UIView.animate(withDuration: 2, delay: 1, options: UIViewAnimationOptions.curveEaseOut, animations: {
                    NSLayoutConstraint(item: self.placeholder, attribute: .left, relatedBy: .equal, toItem: self.searchBar, attribute: .left, multiplier: 1, constant: 5).isActive = true
                }, completion: { (completed) in

                })

            }
        }

有什么建议吗?

为了使 NSLayoutConstraint 动画化,您需要将 setNeedsLayout() 放入动画块中。然后你应该移动

NSLayoutConstraint(item: self.placeholder, attribute: .left, relatedBy: .equal, toItem: self.searchBar, attribute: .left, multiplier: 1, constant: 5).isActive = true

像这样在动画块上方:

NSLayoutConstraint(item: self.placeholder, attribute: .left, relatedBy: .equal, toItem: self.searchBar, attribute: .left, multiplier: 1, constant: 5).isActive = true
UIView.animate(withDuration: 2, delay: 1, options: UIViewAnimationOptions.curveEaseOut, animations: {
    self.layoutIfNeeded()
}, completion: { (completed) in

})

希望对您有所帮助!

带约束的动画可能有点棘手。首先,您需要在动画闭包之外调整所需的约束:

NSLayoutConstraint(item: self.placeholder, attribute: .left, relatedBy: .equal, toItem: self.searchBar, attribute: .left, multiplier: 1, constant: 5).isActive = true

由于约束变化可能导致其他视图改变它们的位置,您需要让超级视图(在大多数情况下是 VC-视图)在动画闭包中布局其子视图:

 UIView.animate(withDuration: 2, delay: 1, options: UIViewAnimationOptions.curveEaseOut, animations: {
      self.view.layoutIfNeeded()
 }, completion: nil)

因此父视图会在动画块中为您调整子视图的位置。