2017-04-26 95 views
0

我有一个键盘通知,我想要它,以便当它停止时,占位符视图动画到搜索栏的左边缘。UIView动画无法与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 

       }) 

      } 
     } 

有什么建议吗?

回答

1

带约束的动画可能有点棘手。首先,你需要调整预期的制约,动画封闭外:

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) 

因此,超级视图调整动画块中的子视图位置。

0

为了动画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 

}) 

希望帮助!