Search code examples
animationswift4nslayoutconstraint

NSLayoutConstraint not animating


Everything animates fine from this code except for the mainViewConstraint. I am trying to make the mainView slide in from the top as it appears by transforming the mainViewConstraint coordinate from -195 to 0. Unfortunately, it is not moving from -195 to 0. It just starts to appear at 0.

import UIKit    

class FirstViewController: UIViewController {

  @IBOutlet weak var bgImage: UIImageView!
  @IBOutlet weak var mainView: UIView!
  @IBOutlet weak var titleLabel: UILabel!
  @IBOutlet weak var findButton: UIButton!
  @IBOutlet weak var mainViewConstraint: NSLayoutConstraint!

  override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    mainViewConstraint.constant = -195

    for i in [mainView, titleLabel, findButton] {
      i?.alpha = 0
    }

    UIView.animate(withDuration: 1, animations: {
    }) { (true) in
      self.animateView()
    }
  }

  func animateView() {
    UIView.animate(withDuration: 2, animations: {
      self.mainView.alpha = 1
      self.mainViewConstraint.constant = 0
      self.view.layoutIfNeeded()

    }) { (true) in
      self.animateLbl()
    }
  }

  func animateLbl() {
    UIView.animate(withDuration: 1, animations: {
      self.titleLabel.alpha = 1
    }) { (true) in
      self.animateBtn()
    }
  }
  func animateBtn() {
    UIView.animate(withDuration: 1) {
      self.findButton.alpha = 1
    }
  }
}

Solution

  • To fix this, I changed the location of the mainViewConstraint to -195 in Storyboards and made the following changes to the code:

        mainViewConstraint.constant = 0 //-195
    
        for i in [mainView, titleLbl, findBtn] {
          i?.alpha = 0
        }
        UIView.animate(withDuration: 1, animations: {
          self.bgImage.alpha = 1
        }) { (true) in
          self.animateView()
        }
      }
    
      func animateView() {
        UIView.animate(withDuration: 2, animations: {
          self.mainView.alpha = 1
          //self.mainViewConstraint.constant = 0
          self.view.layoutIfNeeded()