SwiftUI Expandable Lists (part 1)

Michalis Karagiorgos
2 min readJul 9, 2024

--

A common case that you might need to implement for an iOS app is a list of hierarchical data. Apple’s documentation also provides a tutorial here on how to achieve such a task. But how can you customize the design of the expandable elements?

Step 1

Let’s create our Hierarchical data structure in a way that can support multiple types of UI elements. We are going to make a demo for Sports data.

Now let’s create the mock ListItems

Step 2

We can now create a SwiftUI View that can handle our data and create this Hierarchical Data List. First, let’s begin using a similar implementation with the one that apple provides at the above tutorial.

Default Hierarchical Data List

The problem with the above implementation is that we might need to customize some things like:

  1. remove row separators
  2. remove the insets for the nested elements
  3. change the chevron image and animation

To remove the row separator apple provides the listRowSeparator(.hidden) modifier. But if we try to use it for every element we notice the following

Event Views Missing Row Separator

Only the Event UI Element has a hidden row separator. But why is that? Let’s debug the view and try to find some hints.

OutlineGroup

If you notice carefully the List initializer creates an OutlineGroup. Apple documentation confirms our assumption here. If you search a bit more you can find this nice modifier disclosureGroupStyle(_:) here that can do the trick (unfortunately needs iOS 16+).

Step 3

Create a custom CustomDisclosureGroupStyle to achieve the above customizations.

And consume it inside our View using the modifier

Final Result

Custom Hierarchical List

What if we need though to launch the view with some elements expanded already or trigger expand collapse for some elements programmatically?

Check out the SwiftUI Expandable Lists (part 2)

Thank you!!!

--

--