Member-only story

An Accordion View in Swift and UIKit

Involving constraints

--

Photo by Charlie Solorzano on Unsplash

Difficulty: Beginner | Easy | Normal | Challenging

This article has been developed using Xcode 12.4, and Swift 5.7.2

Prerequisites:

You need to be able to code in Swift, perhaps using Playgrounds

UIKit isn’t dead. Not around these parts at least.

In web design, an accordion is a type of menu that displays a list of headers stacked on top of one another. When clicked on (or triggered by a keyboard interaction or screen reader), these headers will either reveal or hide associated content.

I’m calling this ‘appearing view’ an accordion. I really hope that this doesn’t upset too many readers of this development blog!

Something which looks something like this:

My process

I thought about having an animated view within a UITableView, but once I started to think about it (for the purposes of this blog at least) that felt a little like overkill. A better approach for me would be simply to hide a view and make it appear when the user taps ‘more information’ on the view.

I’m not going to use storyboards for this particular example, but to do the same in the storyboard is more than possible.

This is going to involve using UIStackView, right?

Difficulties

I guess forgetting how to use UIStackView is annoying.

Sure, the header with an image and a UILabel isn’t so difficult

let headerStack = UIStackView(arrangedSubviews: [headerLabel, chevronImageView])
headerStack.axis = .horizontal
headerStack.spacing = 8

I’m then going to have a simple blue background as moreInfoView. I then nestle my infoLabel into this so I get a blue background. Note the height is set to 0 initially so we don’t see this hidden view.

private let moreInfoView: UIView = {
let view = UIView()
view.backgroundColor = .blue…

--

--

No responses yet