Jon K
Jon K

Reputation: 119

UIView Animation Options Repeat count

I'm having some issue with my Swift code, I'm trying to make an UIImageView object fade away and reappear once, but having some issues with having the animation to play only once.

@IBOutlet weak var ball: UIImageView!

@IBAction func onFadeClick(_ sender: Any) {
   UIView.animate(withDuration: 1, delay: 0.0, options: [.repeat, .autoreverse], animations: {
      self.ball.alpha = 0.0
      }, completion: nil)
}

I have attempted to read the documentation and previous questions but all have mentioned to use setAnimationRepeatCount, but xcode has an error stating that it is depreciated in iOS13 (which also does not work). Is there any built in functions I could use to stop the animation after it playing once? I have read somewhere saying using a callback function and reinitialize the animation but I am not exactly sure how to do that. Or is it a better idea to use UIViewPropertyAnimator instead of UIView.animate?

I'm just starting to learn Swift, any help or guidance is appreciated!

Upvotes: 5

Views: 4599

Answers (4)

Alessandro Ornano
Alessandro Ornano

Reputation: 35402

Swift 5.x

The current iOS syntax replacement for deprecated approach could be writed like the example below:

UIView.animate(withDuration:1, 
               delay: 0.5, 
               options: [.curveEaseInOut, .autoreverse, .repeat]) {
     UIView.modifyAnimations(withRepeatCount: 3, autoreverses: true) {
        print("repeated stuff")
     }
} completion: { _ in
     print("done")
}

Upvotes: 4

Marc
Marc

Reputation: 11

instead of the last }) use:

}, completion: { finished in
    self.alpha = 1
})

Upvotes: 0

matt
matt

Reputation: 535566

The iOS 13 replacement for the deprecated approach is https://developer.apple.com/documentation/uikit/uiview/3043564-modifyanimations. Example:

UIView.animate(withDuration:1, animations: {
    UIView.modifyAnimations(withRepeatCount: 3, autoreverses: true, animations: {
       // whatever
    })
})

However, the deprecated approach does still work; it is just deprecated.

Upvotes: 4

CZ54
CZ54

Reputation: 5586

You can use the following to achieve your goal :

UIView.animateKeyframes(withDuration: 2, delay: 0, options: [], animations: {
    UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5) {
         self.ball.alpha = 0.0
    }
    UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5) {
         self.ball.alpha = 1
    }
}) { (isFinished) in

}

Upvotes: 6

Related Questions