UIView动画swift 4 Xcode9的问题

时间:2018-01-24 08:17:54

标签: ios swift animation swift4 xcode9

我正在尝试使用弹簧动画块从屏幕上向中心制作data () { return { ... } }的动画。我在UILabel下面的代码的第一部分工作得很好,但是当我添加动画块时,它就像动画闭包中的代码首先被读取并且它没有动画,因为标签已经在我希望标签动画的地方。我也尝试将这些确切的代码放在viewDidLoad()中,但同样的事情发生了。

viewDidAppear()

2 个答案:

答案 0 :(得分:0)

这是正确的方法(尽管我会尝试将该动画移至viewWillAppearviewDidAppear):

@IBOutlet weak var follow: UILabel!
@IBOutlet weak var followX: NSLayoutConstraint!

override func viewDidLoad() {
    super.viewDidLoad()

    self.follow.translatesAutoresizingMaskIntoConstraints = false

    self.followX.constant = self.view.frame.width/2 + follow.frame.width/2
    self.view.layoutIfNeeded()

    self.followX.constant = 0
    self.view.setNeedsLayout()

    UIView.animate(withDuration: 2, delay: 2, usingSpringWithDamping: 5, initialSpringVelocity: 5, options: .curveEaseOut, animations: {
        self.view.layoutIfNeeded()
    })

}

使用自动布局:

  1. 首先确保开始动画准备就绪:

    self.followX.constant = self.view.frame.width/2 + follow.frame.width/2
    self.view.layoutIfNeeded()
    
  2. 然后将约束更改为动画的最终状态:

    self.followX.constant = 0
    
  3. 然后告诉autolayout约束已更改:

    self.view.setNeedsLayout()
    
  4. 最后,您使用UIView.animate致电layoutIfNeeded()以设置更改动画:

    UIView.animate(withDuration: 2, delay: 2, usingSpringWithDamping: 5, initialSpringVelocity: 5, options: .curveEaseOut, animations: {
        self.view.layoutIfNeeded()
    })
    

答案 1 :(得分:0)

override func viewDidLayoutSubviews() {
   if(once)
   {
      once = false
      self.follow.translatesAutoresizingMaskIntoConstraints = false
      self.followX.constant = self.view.frame.width/2 +   follow.frame.width/2
      self.view.layoutIfNeeded()
   }

}

并在viewDidAppear

 override func viewDidAppear() {

   self.followX.constant = 0
   UIView.animate(withDuration: 2, delay: 0, usingSpringWithDamping: 5, initialSpringVelocity: 5, options: .curveEaseOut, animations: {
      self.view.layoutIfNeeded()
  })

 }