Entrance animation with UIStackView

I’ve been playing around with UIStackView for a while and wanted to share some of my findings.

One really neat thing is that you can get size and position animation of a UIStackView’s children for free. Just by changing a UIView’s hidden property from false to true inside an animation block will make the view shrink animated. While the view, which is about the be hidden, is starting to shrink the view below will automatically start to animate its position, all for free.

The video below shows a nice entrance effect where the labels appears to fall down from the top and slowly fade in.

The Xcode project can be found here but I also included the view controller code in the article to give you an idea of how easy it is to setup. I added a pinch of functional programming style to spice up the code a bit.

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var stackView: UIStackView!

override func viewDidAppear(animated: Bool) { ... }
    @IBAction func play() {
stackView.arrangedSubviews
.forEach(stackView.removeArrangedSubview)

let items = ["Working", "with", "UIStackView", "is", "fun"]

items
.map(labelFromText)
.forEach(addViewToStackView)

stackView.arrangedSubviews
.forEach(applyUnhideAnimationForView)
}
    private func labelFromText(text: String) -> UILabel { ... }

private func addViewToStackView(view: UIView) { ... }
    private func applyUnhideAnimationForView(view: UIView) {
UIView.animateWithDuration(1, delay: 0,
usingSpringWithDamping: 0.9, initialSpringVelocity: 1,
options: [],
animations: {
view.alpha = 1
view.hidden = false
},
completion: nil)
}
}

Thanks for reading.