简体   繁体   中英

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.

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

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 (eg 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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM