0

I'm trying to animate a UILabel using Cartography and using this code:

    let group = ConstraintGroup()

    constrain(alertLabel, replace: group) { alertLabel in
        alertLabel.centerX  == alertLabel.superview!.centerX
        alertLabel.width == alertLabel.superview!.width * Constants.alertLabelWidthMultiplier
        alertLabel.bottom == alertLabel.superview!.top + 0
    }

    constrain(alertLabel, replace: group) { alertLabel in
        alertLabel.centerX  == alertLabel.superview!.centerX
        alertLabel.width == alertLabel.superview!.width * Constants.alertLabelWidthMultiplier
        alertLabel.bottom == alertLabel.superview!.top + 60
    }

    UIView.animateWithDuration(0.5, animations: alertLabel.layoutIfNeeded)

enter image description here

I want my UILabel to be centered in the beginning and end of the animation. However, it seems to start on the top left corner of the superview instead. What am I doing wrong here?

etayluz
  • 15,920
  • 23
  • 106
  • 151

1 Answers1

2

The problem was with this line:

UIView.animateWithDuration(0.5, animations: alertLabel.layoutIfNeeded)

It should be:

UIView.animateWithDuration(0.5, animations: alertLabel.superview!.layoutIfNeeded)

The centerX relational NSLayoutConstraint is on the superview - thus it's the superview that needs layoutIfNeeded called upon.

etayluz
  • 15,920
  • 23
  • 106
  • 151