2015-08-31 31 views
0

我正在嘗試使用animateWithDuration來更新UIView的位置。當動畫開始發生時,UIView開始更新,但完成後會跳轉到正確的位置。這是告訴我,UIView的框架設置不正確,但我不明白爲什麼。這裏是代碼:Swift UIView框架在animateWithDuration內沒有正確更新

func showInfoView() { 

    infoView.hidden = false 
    let newPosition = self.view.frame.height - (self.infoView.frame.height + 260) 

    UIView.animateWithDuration(2.0, animations: { 
     // Set the view to have the new y position 
     self.infoView.frame.origin.y = newPosition 
     }, completion: { finished in 

      // Remove previous constraint 
      if (self.hintConstraint != nil) { 
       self.view.removeConstraint(self.hintConstraint) 
      } 

      // Create the new constraint 
      self.hintConstraint = NSLayoutConstraint(item: self.infoView, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1, constant: newPosition) 
      self.view.addConstraint(self.hintConstraint) 
    }) 
} 

任何人都可以幫助我理解爲什麼y代碼沒有在代碼中正確設置?

回答

2

如果您嘗試使用約束進行動畫製作,則應改爲更改約束,然後在父視圖上的動畫塊中調用layoutIfNeeded

1)動畫塊

2)在動畫塊的外側設置新的約束,稱之爲layoutIfNeeded上父視圖。

func showInfoView() { 

    infoView.hidden = false 
    let newPosition = self.view.frame.height - (self.infoView.frame.height + 260) 
    self.hintConstraint = NSLayoutConstraint(item: self.infoView, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1, constant: newPosition) 

    UIView.animateWithDuration(2.0, animations: { 
     self.view.layoutIfNeeded() 
    }) 
} 
+0

謝謝。我不知道你必須在動畫塊之外設置約束。 –