How to implement a dropdown button in SwiftUI

Joshua Jiang
2 min readFeb 23, 2020

[To help people who want to save money from tracking their expenses, I have released a new app write completely in SwiftUI. Let me know in the comment about how I can improve it: https://apps.apple.com/us/app/flow-spending-flow/id1504019591?ls=1]

When I was writing my first SwiftUI application, and my designer sent me this image.

A dropdown so users can quickly select day range (https://www.stephaniecorrales.com/)

Unfortunately, StackOverflow could not help me a lot with this problem at that time, so I need to come up with my solution for this component.

Setup and styling

Before we add the ability to invoke dropdown and select a dropdown item. We need to have a button and dropdown ready and define our object.

Now with preview

we can see our dropdown

Now we have both components to be ready, we can implement functionality to invoke the dropdown.

Bring life to the dropdown button

The trick here is to use add a dropdown to the overlay instead of adding to the VStack because adding outside the overlay will make the size of our dropdown button change and result in messing up parent’s layout.

Wanna adding some animation?

Unfortunately, till now I cannot find the way to animate expanding the dropdown (https://www.youtube.com/watch?v=CwD4cScGCq8). If anyone knows how to do it, please let me know.

--

--