Creating an Expandable Button in Swift

Ale Patrón
The Startup
Published in
2 min readJun 14, 2020

--

We’re going to build a custom expandable button in Swift, like the one below:

First off, it’s important to understand the view structure that is necessary to implement a component like this one.

We will create a subclass of UIView that will be composed of 5 subviews like so:

  1. A containerStackView that will hold the menuButton and the expandedStackView
  2. A menuButton that, when tapped, will handle the expanding animation
  3. An expandedStackView that will be shown or hidden when the menuButton is tapped
  4. A dogButton that will be part of the expandedStackView
  5. A catButton that will also be part of the expandedStackView
Button Panel View Structure
Button Panel View Structure. The arrow signals the stack view that will be shown and hidden to emulate the expand and collapse animations, respectively.

Creating our custom UIView

Let’s start by setting up our view, which we will call ButtonPanelView. We will first create 3 instances of UIButton and 2 instances of UIStackView.

We will add dogButton and catButton as arranged subviews of expandedStackView. We will then add expandedStackView and menuButton as arranged subviews of containerStackView.

--

--