How to let CATransaction repeat infinitely? - Swift

807 views Asked by At

I have an animate function which contains CATransaction.begin() I want this animation to be repeated infinitely or for a defined number of times. How do I make that happen?

This is the animate function if you need to see the code:

 private func animate(views: [UIView], duration: TimeInterval, intervalDelay: TimeInterval) {

        CATransaction.begin()
        CATransaction.setCompletionBlock {
            print("COMPLETED ALL ANIMATIONS")
        }

        var delay: TimeInterval = 0.0
        let interval = duration / TimeInterval(views.count)

        for view in views {
            let transform = view.transform

            UIView.animate(withDuration: interval, delay: delay, options: [.curveEaseIn], animations: {

                view.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)

            }, completion: { (finished) in

                UIView.animate(withDuration: interval, delay: 0.0, options: [.curveEaseIn], animations: {

                    view.transform = transform

                }, completion: { (finished) in


                })
            })

            delay += (interval * 2.0) + intervalDelay
        }
        CATransaction.commit()
    }
1

There are 1 answers

7
MichaelV On

I think CATransaction redundant there

If I understand what you want to achieve

UIView.animate(withDuration: interval, delay: delay, options: [.curveEaseIn, .autoreverse, .repeat], animations: { 
    self.views.forEach{$0.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)}
}, completion: nil)

EDIT: Recursive function to do pulse in circles

func pulse(index: Int) {
    guard views.count > 0 else { return }
    let resolvedIndex = (views.count < index) ? index : 0
    let duration = 1.0
    let view = views[resolvedIndex]
    UIView.animate(withDuration: duration, delay: 0, options: [.curveEaseIn,.autoreverse], animations: {
        self.view.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
    }) { [weak self] _ in
        self?.pulse(index: resolvedIndex + 1)
    }
}