Animating an automatic layout constraint constant X to the center of the parent view
I'll do it briefly and in detail for you. What I am still doing:
1) I created an exit for the required constraints (Center X Alignment). I don't know if this matters, but I changed the multiplier for my needs (3: 1)
2) Animating it constant
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.btn_option_layout.constant = self.nan_view.center.x //Get center x value
self.nan_view.layoutIfNeeded() // Parent View
})
Problem:
Initial position of the object:
Instead of animating the view at the center X like this:
It animates it for some reason on the left, here is the result:
Hope I was clear enough. Thank you for your time.
What is the correct way to calculate the constants constants to center it on X?
source to share
solvable. Despite @ matt's excellent answer (and works). The main purpose of my question was to handle persistent constraints to center it on X. By a formula that could show me:
**a1 = m*a2 + c**
I dived. I figured out a few points: Ultimately I need the second attribute (a2 - button.center.x
) to be in the same position of the first attribute (a1 - self.view.center.x
). so a1 = a2 = self.view.center.x
My factor is 3 (m is the factor). And C .. well, we're looking for it :), so let's put that on:
a1 = m*a2 + c
c = a1 - m* a2
c = self.view.center.x - 3 * self.view.center.x
c = -2 * self.view.center.x
Code:
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.btn_option_layout.constant = -2 * self.nan_view.center.x
self.nan_view.layoutIfNeeded()
})
And bring it back to its original location:
Code:
UIView.animateWithDuration(0.5, animations: { () -> Void
self.btn_option_layout.constant = 0
self.nan_view.layoutIfNeeded()
})
Hope this helps. and matte thanks for the directions!
source to share
What you are trying to do is for sure. You have a constraint that links the center of one view to the center of another view. If the multiplier for this constraint is 1, the view will be centered on the other view.
But your multiplier is not 1. And, as you rightly pointed out, you cannot change the multiplier of an existing constraint - it is read-only.
But not a problem. Just replace the entire constraint with another constraint that is identical to the first, except that its multiplier is 1. Now, leave the layout! It is a little known fact that you can animate this constraint change.
Here is the actual code:
let con2 = NSLayoutConstraint(item: self.con.firstItem, attribute: self.con.firstAttribute, relatedBy: self.con.relation, toItem: self.con.secondItem, attribute: self.con.secondAttribute, multiplier: 1, constant: 0)
NSLayoutConstraint.deactivateConstraints([self.con])
NSLayoutConstraint.activateConstraints([con2])
UIView.animateWithDuration(1, animations: {self.view.layoutIfNeeded()})
And here's a gif loop that shows the resulting animation to the center:
source to share