Search code examples
iosnslayoutconstraint

Animate centre vertically constraint to fixed from top


I'm trying to animate a UILabel that to begin with is centered vertically and horizontally in a view so that it ends up 40 points from the top.

Due to the fact that this is on multiple devices/screen sizes I don't think I can use a top constraint as then the items wouldn't necessarily be in the correct place to begin with and similarly there wouldn't be a 'constant' value to use that would work across all device heights

What's the best way of going about this? Am I better off have 2 constraints, 1 for the vertical center to begin with and then one for the top position at the end of the animation and then switching these out in the animation?

So far I just have an IBOutlet for my centerY constraint and I tried to override like so:

    labelYConstraint = NSLayoutConstraint.init(item: titleLabel, attribute:NSLayoutAttribute.centerY , relatedBy: .equal, toItem: view, attribute: NSLayoutAttribute.top, multiplier: 0, constant: 40)

    UIView.animate(withDuration: 2.0) {
        self.view.layoutIfNeeded()
    }

Anyone managed to achieve something similar?


Solution

  • You need to deactivate the previously-set constraint first:

    labelYConstraint.active = false
    labelYConstraint = NSLayoutConstraint.init(item: titleLabel, attribute:NSLayoutAttribute.centerY , relatedBy: .equal, toItem: view, attribute: NSLayoutAttribute.top, multiplier: 0, constant: 40)
    view.addConstraint(labelYConstraint)