Reputation: 217
just quick inquiry in regards to implementing an issue I'm having with animating a UIImageView. I successfully implemented animating an image to slide off screen; but i want it to reappear when it exists the view to simulate a side-scroller game animation.
I've tried implementing a completion handler but struggled understanding the logic of how to implement it, so I removed my attempts; so my code is left as follows:
let oldCenter = background.center
let newCenter = CGPoint(x: oldCenter.x - 400, y: oldCenter.y)
UIView.animate(withDuration: 2, delay: 0, options: .curveLinear, animations: {
self.background.center = newCenter
}) { (success: Bool) in
print("Done moving image")
}
An example or pointers on how to achieved my desired animation would be appreciated!
Upvotes: 1
Views: 1151
Reputation: 66
let oldCenter = view.center
let newCenter = CGPoint(x: oldCenter.x - 400, y: oldCenter.y)
UIView.animate(withDuration: 2.0, delay: 0.0, options:
[.curveLinear, .repeat], animations: {
view.center = newCenter
}, completion: nil)
Upvotes: 3
Reputation: 31645
If you want to repeat the animation,
there is no need to implement the completion
.
animate(withDuration:delay:options:animations:completion:) has options
parameter (UIViewAnimationOptions), which is:
A mask of options indicating how you want to perform the animations. For a list of valid constants, see UIViewAnimationOptions.
One of the constants for the UIViewAnimationOptions
is repeat
:
Repeat the animation indefinitely.
So, what you should do:
UIView.animateKeyframes(withDuration: 2.0, delay: 0.0, options: [.curveLinear, .repeat], animations: {
self.background.center = newCenter
}, completion: nil)
Again, implementing completion
is not required for repeating the animation, implementing it is up to your case.
Upvotes: 1
Reputation: 5420
You can try UIView UIView repeat option
let oldCenter = background.center
let newCenter = CGPoint(x: oldCenter.x - 400, y: oldCenter.y)
UIView.animate(withDuration: 2, delay: 0, options: [.curveLinear, repeat], animations: {
self.background.center = newCenter
}) { (success: Bool) in
print("Done moving image")
if(success)
{
self.background.center = oldCenter
}
}
Upvotes: 0