erginbilgin
erginbilgin

Reputation: 86

Repeating alpha animation in Swift

I am trying to achieve a pulse like effect for views in a UITableViewCell on iOS using Swift. Requirement is 2 second animation starting from alpha 1.0 to 0.5 and then back to 1.0. And repeating infinitely.

I tried few approaches but animations never start, or repeat.

view being a simple UIView outlet:

@IBOutlet private weak var view: UIView!

Tried variants:

UIView.animateKeyframes(withDuration: 2.0, delay: 0, options: [], animations: {
    UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5, animations: {
        view.alpha = 0.0
    })
    UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5, animations: {
        view.alpha = 1.0
    })
}, completion: nil)
let animationDuration = 1.0
UIView.animate(withDuration: animationDuration,
               delay: 0,
               options: [.repeat, .autoreverse],
               animations: {
                   view.alpha = 0.5
               },
               completion: nil)

both approaches were triggered in awakeFromNib() if makes sense.

Upvotes: 1

Views: 730

Answers (1)

erginbilgin
erginbilgin

Reputation: 86

Triggering animations in prepareForReuse() instead of awakeFromNib() does the magic. As @matt mentioned in his comment, views are not present in hierarchy at awakeFromNib() which looks like necessary for animations to start.

Upvotes: 1

Related Questions