2017-04-26 90 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 

}) 

希望幫助!