[英]issues with UIView animation swift 4 Xcode9
我正在尝试使用弹簧动画块从屏幕外到中心制作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()
})
}
这是正确的方法(尽管我会尝试将动画移动到viewWillAppear
或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()
self.followX.constant = 0
self.view.setNeedsLayout()
UIView.animate(withDuration: 2, delay: 2, usingSpringWithDamping: 5, initialSpringVelocity: 5, options: .curveEaseOut, animations: {
self.view.layoutIfNeeded()
})
}
要使用自动版式,请执行以下操作:
首先,请确保准备开始动画:
self.followX.constant = self.view.frame.width/2 + follow.frame.width/2 self.view.layoutIfNeeded()
然后将约束更改为动画的最终状态:
self.followX.constant = 0
然后,您告诉autolayout约束已更改:
self.view.setNeedsLayout()
最后,使用layoutIfNeeded()
调用UIView.animate
来使更改生效:
UIView.animate(withDuration: 2, delay: 2, usingSpringWithDamping: 5, initialSpringVelocity: 5, options: .curveEaseOut, animations: { self.view.layoutIfNeeded() })
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()
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.