Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update the constant property of a constraint programmatically in Swift?

I want to animate an object, so I declare a constraint and add it to the view. I then update the constant property of the constraint inside an UIView animation. Why doesn't this code move the object?

UIView.animateWithDuration(1, animations: {
     myConstraint.constant = 0   
     self.view.updateConstraints(myConstraint)
})
like image 294
Cesare Avatar asked Jan 24 '15 15:01

Cesare


People also ask

How do I change a constraint in Swift?

Select the height constraint from the Interface builder and take an outlet of it. So, when you want to change the height of the view you can use the below code. Method updateConstraints() is an instance method of UIView . It is helpful when you are setting the constraints programmatically.

How do I change constraints in Xcode?

Clicking the Edit button in any of the constraints brings up a popover where you can change the constraint's relationship, constant, priority, or multiplier. To make additional changes, double-click the constraint to select it and open it in the Attribute inspector.

What is NSLayoutConstraint?

The relationship between two user interface objects that must be satisfied by the constraint-based layout system.


1 Answers

In order to declare an animation, you cannot re-define the constraint and call updateConstraints. You are supposed to change the constant of your constraint and follow the format below:

self.view.layoutIfNeeded() UIView.animate(withDuration: 1) {     self.sampleConstraint.constant = 20     self.view.layoutIfNeeded() } 
like image 107
duan Avatar answered Sep 22 '22 13:09

duan