Make animation easy with UIStackView's

Learn how to remove and add subviews with animations

In this SwiftTip, you will learn how to animate views in and out in a way that automatically adjusts surrounding views. This is easy with the help of a UIStackView, let's see how.

We start by creating a UIStackView and filling it with 3 simple UIView's - each view's background color matches its name. We then tell the UIStackView to layout its subviews horizontally and to give them equal widths by settings the distribution property on stackView to be fillEqually.

let redView = UIView()
redView.backgroundColor = .red
let greenView = UIView()
greenView.backgroundColor = .green
let blueView = UIView()
blueView.backgroundColor = .blue

let stackView = UIStackView(arrangedSubviews: [redView, greenView, blueView])
stackView.axis = .horizontal
stackView.distribution = .fillEqually
stackView.frame = CGRect(x: 0.0, y: 50.0, width: 300.0, height: 200.0)

To give the appearance of one of our UIView's animating in, we first set that UIView's isHidden property to be true. Then, inside an animation block, we change that same UIView's isHidden property to be false.

greenView.isHidden = true
UIView.animate(withDuration: 2.0, animations: {
greenView.isHidden = false
})

To animate a UIView out, we do the opposite - start by making sure its isHidden property has a value of false, and then we change isHidden to be true in an animation block.

greenView.isHidden = false
UIView.animate(withDuration: 2.0, animations: {
greenView.isHidden = true
})

Full Code

let frame = CGRect(x: 0.0, y: 0.0, width: 300.0, height: 300.0)
let containerView = UIView(frame: frame)
containerView.backgroundColor = .black

PlaygroundPage.current.liveView = containerView

let redView = UIView()
redView.backgroundColor = .red
let greenView = UIView()
greenView.backgroundColor = .green
let blueView = UIView()
blueView.backgroundColor = .blue

let stackView = UIStackView(arrangedSubviews: [redView, greenView, blueView])
stackView.axis = .horizontal
stackView.distribution = .fillEqually
stackView.frame = CGRect(x: 0.0, y: 50.0, width: 300.0, height: 200.0)

containerView.addSubview(stackView)

// animate in
greenView.isHidden = true
UIView.animate(withDuration: 2.0, animations: {
    greenView.isHidden = false
})

// animate out
greenView.isHidden = false
UIView.animate(withDuration: 2.0, animations: {
    greenView.isHidden = true
})

* This article originally appeared in the ZipTips app.

Sponsor

earlybirdee

Get your next tech job faster. Be the first to apply to today and yesterday’s newest jobs. Only the freshest jobs are available. Older than 48 hours — poof!

Want to connect?

Contact me to talk about this article, working together or something else.