SwiftUI Expandable Lists (part 1)
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.
The problem with the above implementation is that we might need to customize some things like:
- remove row separators
- remove the insets for the nested elements
- 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
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.
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
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!!!