NSLayoutConstraint 没有动画

NSLayoutConstraint not animating

除 mainViewConstraint 之外,此代码中的所有内容都可以很好地进行动画处理。我试图通过将 mainViewConstraint 坐标从 -195 转换为 0 来使 mainView 从顶部滑入。不幸的是,它没有从 -195 移动到 0。它只是从 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
    }
  }
}

在您的代码中,您在动画块内调用 animateView(),这似乎是问题所在。

将其移出动画块应该可以解决问题。

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

mainViewConstraint.constant = -195

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

self.animateView()

}

为了解决这个问题,我在故事板中将 mainViewConstraint 的位置更改为 -195,并对代码进行了以下更改:

    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()