I am trying to make an animation of a UILabel
from off the screen to the center with a spring animation block. The first part of my code below in viewDidLoad()
works perfectly, but when I add the animation block, it's like the code in the closure of the animation gets read first and it doesn't animate because the label is already in the place where I want the label to animate to. I have also tried to put this exact code in viewDidAppear()
but the same thing happens.
@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()
})
}
This is the correct way to do it (although I would try to move that animation to viewWillAppear
or 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()
})
}
To work with autolayout:
You first make sure the to begin animation is ready:
self.followX.constant = self.view.frame.width/2 + follow.frame.width/2 self.view.layoutIfNeeded()
Then you change constraints to the final state of the animation:
self.followX.constant = 0
Then you tell autolayout that the constraints were changed:
self.view.setNeedsLayout()
And finally you call UIView.animate
with layoutIfNeeded()
to animate the change:
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()
}
}
and in viewDidAppear
override func viewDidAppear() {
self.followX.constant = 0
UIView.animate(withDuration: 2, delay: 0, usingSpringWithDamping: 5, initialSpringVelocity: 5, options: .curveEaseOut, animations: {
self.view.layoutIfNeeded()
})
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.