Reputation: 1358
I've started my journey from Objective-C to Swift (starting with UIKit) and I've run into a scenario I have a solution for in Objective-C, but am struggling to solve for with Swift:
I have an image and I want to animate the UIImageView's position. So far, this is what I've got and it's working as intended (my cloud moves back and forth on the x-axis with a linear motion:
let cloudImageFile = UIImage(named:"cloud.png")
let cloudImage = UIImageView(image: cloudImageFile!)
cloudImage.frame = CGRect(x: 200, y: 0, width: 80, height: 80)
animationView.addSubview(cloudImage)
UIView.animate(withDuration: 4.0, delay: 0, options: [.curveLinear, .autoreverse, .repeat], animations: {
cloudImage.frame = CGRect(x:-80, y:0, width: 80, height: 80)
}, completion: nil)
What I'd like to do is wait before the autoreverse. Is there an option for this, or a standard approach? In Objective-C my solution was to hide, reset my positions, and use a timeout and then recall the animation. I used that for years and it worked well, but I have the feeling that was a hack unto itself and am curious how people handle this.
For example, I could imagine NOT auto reversing, and in completion block wait, then animate the cloud back to starting position and recalling the animation?
Side Question: I tried setting UIImageView to a var as I assumed changing the CGRect is a mutation, but XCode is suggesting I use let as it's not mutated. Is the animation not actually changing the struct inside the UIImageView?
EDIT: Is animateWithKeyframes what I'm looking for
Animate X1 -> X2 (animate x position)
Animate X2 -> X3 (X2 and X3 are the same value, result is not moving for a duration of 1/4 seconds)
Animate X3 -> X1 (animate x position back)
Loop
EDIT: I found an answer that works for me
func cloud() {
cloudImage.frame = CGRect(x: 200, y: 0, width: 80, height: 80)
UIView.animate(withDuration: 4.0, delay: 2.0, options: [.curveLinear], animations: {
self.cloudImage.frame = CGRect(x:-80, y:0, width: 80, height: 80)
}, completion: {_ in
self.cloud()
})
}
Wrapped the animation in a function and called it again on completion. This allows me to set duration and also reset the values. no idea what _ in is... eye roll I still miss objective-c.
Upvotes: 0
Views: 23