Josué H.
Josué H.

Reputation: 1191

Animation each UIView inside the StackView

I need to animate a UIViews inside stackView like this.

enter image description here

This image is a gif 👆🏻 (click to show)

I create an UIView Extension like this

func fadeIn(duration: TimeInterval = 1.5, delay: TimeInterval = 0.0, completion: @escaping ((Bool) -> Void) = {(_: Bool) -> Void in }) {
            self.alpha = 0.0

            UIView.animate(withDuration: duration, delay: delay, options: UIView.AnimationOptions.curveEaseIn, animations: {
                self.isHidden = false
                self.alpha = 1.0
            }, completion: completion)
        }

And for each UIView inside the StackView assigned the animation like this

stackView.subviews.forEach { currentView in
    currentView.fadeIn()
}

but all views appear at the same time. I try to add a delay time but doesn't work correctly. Any idea how to fix?

Upvotes: 0

Views: 64

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100541

You can try

stackView.arrangedSubviews.enumerated().forEach { (index,item) in
   item.fadeIn(delay:Double(index)*1.5)
}

with

 func fadeIn(duration: TimeInterval = 1.5, delay: TimeInterval = 0.0, completion: @escaping ((Bool) -> Void) = {(_: Bool) -> Void in }) {
   self.alpha = 0.0
   UIView.animate(withDuration: duration, delay: delay, options: UIView.AnimationOptions.curveEaseIn, animations: {
     self.isHidden = false
     self.alpha = 1.0
   }, completion: completion)
}

Upvotes: 2

Related Questions