2016-11-20 76 views
0
override func viewDidAppear(_ animated: Bool) { 
    super.viewDidAppear(animated) 
    UIView.animate(withDuration: 0.5, animations: { 
     self.animateLabel.center.x += 30 
    }) 
} 

上標籤:水平和垂直中心。 下標籤:對齊導致上標籤,垂直空間與上標籤。自動佈局和viewAnimation之間的關係是什麼?

然後我把上面的代碼中的ViewController動畫上部標籤:

然後運行該模擬器。

正如你所看到的,這兩個標籤不再對齊。這是否意味着我之前設置的自動佈局規則已被打破? 然而,當我旋轉模擬器時,上面的標籤回到中心位置。 自動佈局和viewAnimation之間的關係是什麼?

enter image description hereenter image description hereenter image description here

回答

1

這不是動畫本身這是問題,它正在改變視圖的frame直接,是造成你的問題。

本質上,自動佈局使用您設置的約束來計算每個視圖的框架。直接修改frame(或者通過修改center屬性隱式修改),則實際上將覆蓋自動佈局過程的結果,並重新定位視圖。

任何導致自動佈局進程再次運行的事件都會導致根據約束重新計算該幀。旋轉設備將導致重新計算,如調用self.animateLabel.setNeedsLayout

當您使用自動佈局時,您不應該直接重新定位視圖;你應該修改約束,然後觸發自動佈局來移動視圖。

假設您正在使用故事板,則應該爲上標籤的水平中心約束創建@IBOutlet。然後,您可以製作此約束的動畫:

override func viewDidAppear(_ animated: Bool) { 
    super.viewDidAppear(animated) 
    self.animateLabel.layoutIfNeeded() // Ensure auto layout is complete 
    self.labelCentreConstraint.Constant = 30 
    UIView.animate(withDuration: 0.5, animations: { 
     self.animateLabel.layoutIfneeded() // Recalculate auto layout 
    }) 
} 
相關問題