【问题标题】:issues with UIView animation swift 4 Xcode9UIView 动画 swift 4 Xcode9 的问题
【发布时间】:2018-01-24 08:17:53
【问题描述】:

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

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

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

}

【问题讨论】:

  • 你解决了吗?

标签: ios swift animation swift4 xcode9


【解决方案1】:

这是正确的做法(尽管我会尝试将该动画移至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. 然后你告诉自动布局约束已经改变:

    self.view.setNeedsLayout()
    
  4. 最后你用layoutIfNeeded() 调用UIView.animate 来为更改设置动画:

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

【讨论】:

  • 是的,它奏效了。非常感谢,我这几天一直在为动画苦苦挣扎!
  • @nicholasdmoore 你也可以点个赞吗? :)
  • 它说投票已投并记录,但由于我的分数低于 15 分或其他内容,因此没有公开显示
  • @nicholasdmoore 好的,别担心......无论如何,祝你编码顺利
【解决方案2】:
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()
  })

 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-19
    • 2013-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多