[英]How to animate a UIImage constraints in Swift 4
我正在制作卡片應用程序,並且需要制作動畫,以便卡片可以更改其約束以移動到另一個地方。 我將如何為UIImage執行此操作。
鈎住UIImageView的前導,尾隨CenterX或CenterY約束,然后執行此操作
self.imageLeadCon.constant = // value
UIView.animate(withDuration: 3.0 , animations: {
self.view.layoutIfNeeded()
// animation
}, completion: { _ in
// completion
})
我認為您將UIImage
與UIImageView
混淆了。 第一個是圖像的數據表示形式,第二個是顯示UIImage
的視圖。
所以我想您想在UIImageView
周圍移動。 為此,獲得對約束的引用(例如,通過ctrl從情節UIViewController
的約束拖動到UIViewController
實例)。
之后,您可以像下面這樣在動畫塊中更新約束:
// Make sure the view is laid out as Mischanya Schtrigel stated
self.view.layoutIfNeeded()
UIView.animate(withDuration: 0.5) { // duration in seconds
myConstraint.constant = 50 // update your constraint here
self.view.layoutIfNeeded()
}
與其他答案相反,我喜歡在動畫閉包中放置約束更改,以使其更清楚要動畫的內容。
首先,您必須將約束拖放到視圖控制器中,以建立出口。 使用UIImageView
或UITableView
等的相同方法。
實際上,對於那些看過WWDC(我猜是2014年)的人,蘋果已經解釋了如何以正確的方式對UI進行動畫處理。
首先,您必須調用layoutIfNeeded()
方法以確保視圖上的所有內容都已布局。 在可以更改約束之后, layoutIfNeeded()
在動畫塊中,調用layoutIfNeeded()
方法以使用新值對約束進行布局。
因此代碼應如下所示:
view.layoutIfNeeded() // to make sure your view have laid out
self.constraint.constant = //change your constant to any value
UIView.animate(withDuration: 1.0) {
self.view.layoutIfNeeded() //layout your constraint with the new value
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.