How to animate a UIImage constraints in Swift 4

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.

3 answers

  • answered 2018-01-15 19:30 Sh_Khan

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

    self.imageLeadCon.constant = // value
    UIView.animate(withDuration: 3.0 ,  animations: {
        // animation
    }, completion: { _ in
        // completion

  • answered 2018-01-15 19:36 fl034

    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'll need an animation block like here:

    UIView.animate(withDuration: 0.5) { // duration in seconds
        // update your constraints here

  • answered 2018-01-15 21:04 Mischanya Schtrigel

    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