UIStackView Tutorial for iOS: Introducing Stack Views

Learn how to simplify your iOS layouts with UIStackView. Layout a series of views horizontally or vertically, using alignment, distribution and spacing. By Ehab Amer.

Leave a rating/review
Download materials
Save for later
Share
You are currently viewing page 4 of 4 of this article. Click here to view the first page.

Animation

Currently, the app is very jumpy when hiding and showing the weather details. You’ll add some animation to smooth the transition.

Stack views are compatible with the UIView animation engine. This means that animating the appearance or disappearance of an arranged subview is as simple as toggling its isHidden property inside an animation block.

Changing the isHidden property of an arranged subview updates the layout of its parent Stack View. If that update is in an animation block, it would be just the same if you changed the layout yourself in the animation block.

It’s time to write some code! Open SpotInfoViewController.swift and take a look at updateWeatherInfoViews(hideWeatherInfo:animated:).

You’ll see these lines at the end of the method:

weatherHideOrShowButton.setTitle(newButtonTitle, for: .normal)
weatherInfoLabel.hidden = shouldHideWeatherInfo

Replace them with the following:

if animated {
  UIView.animate(withDuration: 0.3) {
    self.weatherHideOrShowButton.setTitle(newButtonTitle, for: .normal)
    self.weatherInfoLabel.isHidden = shouldHideWeatherInfo
  }
} else {
  weatherHideOrShowButton.setTitle(newButtonTitle, for: .normal)
  weatherInfoLabel.isHidden = shouldHideWeatherInfo
}

Build and run, and tap the Hide or Show button. Doesn’t the animated version feel much nicer?

In addition to animating the hidden property on views contained within the stack view, you can also animate properties on the stack view itself, such as alignment, distribution, spacing and even the axis.

Where to Go From Here?

You can download the completed version of the project using the Download Materials button at the top or bottom of this tutorial. Here are some resources for further study:

If you have any questions or comments, please don’t hesitate to join the forum discussion below.