NSLayoutConstraint没有动画

时间:2018-06-24 20:22:28

标签: animation swift4 nslayoutconstraint

除了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
    }
  }
}

2 个答案:

答案 0 :(得分:0)

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

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

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

mainViewConstraint.constant = -195

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

self.animateView()

}

答案 1 :(得分:0)

为解决此问题,我在情节提要中将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()