0

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
  • You can change the leading/trailing constant value of UIImage and then call UIView.animateWithDuration(duration){ self.view.layoutIfNeeded() }. Do some research please. You need to learn it properly instead of just asking it here... Commented Jan 15, 2018 at 19:31

3 Answers 3

1

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
})
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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
}

1 Comment

What if you made your constraint programmatically. How could you change it. I tried doing something like: copyImages.imageViewBottom.layoutIfNeeded() self.topAnchor.constraint(equalTo: view.topAnchor, constant: 20).isActive = true Though it's not working

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.