How to animate a UIImage constraints in Swift 4

妖精的绣舞 提交于 2019-12-11 16:33:23

问题


I am making a card app and I need to make an animation so that a card would change its constraints to move to another place. How would I do this for a UIImage.


回答1:


First of all you have to drag and drop your constraint into your view controller, to make an outlet. The same way you are doing it with UIImageView or UITableView, etc.

Actually, for those who have watched WWDC (2014 I guess), Apple have explained how to animate UI in the proper way.

Firstly, you have to call layoutIfNeeded() method to make sure that everything on your view have laid out. After you can change your constraint and right after that in your animation block you call layoutIfNeeded() method to layout your constraint with the new value.

So code should look like that:

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
}



回答2:


Hook the leading , trailing , CenterX OR CenterY constraint of the UIImageView and do this

self.imageLeadCon.constant = // value

UIView.animate(withDuration: 3.0 ,  animations: {

   self.view.layoutIfNeeded()

    // animation
}, completion: { _ in

    // completion
})



回答3:


I think you're confusing UIImage with UIImageView. The first one is the image's data representation, the second one is the View that displays the UIImage.

So I guess you want to move around the UIImageView. To do that obtain a reference to the constraints (e.g. by ctrl-dragging from the constraint in the storyboard to your UIViewController instance).

After that you can update the constraint in an animation block like here:

// 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()
}

Contrary to the other answers, I like putting the constraint changes in the animation closure to make it more clear what is going to be animated.



来源:https://stackoverflow.com/questions/48269404/how-to-animate-a-uiimage-constraints-in-swift-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!