An Outline Picker for SwiftUI

If you want to display an outline in SwiftUI you may use the framework supplied OutlineGroup construct. That’s based on a nested tree of DisclosureGroup and is quite nice. But on appearance of the OutlineGroup all outlines are collapsed. Well, in one of my projects I wanted to display the outline all expanded on show up. No way to do that with OutlineGroup as far as I know. But then I found this nice variant ( with a control of expansion:

Basically, it’s recreating the OutlineGroup with the additional parameter isExpanded. And, in my version, it’s displaying the leafs correctly if the child’s array is nil or it is empty.

Today I need to select an item from an outline. It should behave very similar to the standard Picker in SwiftUI. But Picker does not accept an outline to pick from. So, we do have to invent that by ourself.

On the left hand side you see my example app with the selection from a plain array with Picker. And the same should work with an outline like here on the right hand side:

Looks nice, doesn’t it?

Here is the implementation of my OutlinePicker:

Yes, it’s a little bit lengthy. Let’s take a look in some more detail.

Lines 2 – 7 represent the parameters of our new construct:

  • title: the title string of our Picker
  • nodes: the array of Node which build the outline tree
  • childKeyPath: the path to the array of child nodes
  • isExpanded: the flag to control whether the outline is expanded on startup or not
  • selection: the selected node on startup and dismissal
  • content: the display of node

This will be used like this:

The first 5 lines show the usage of the standard Picker in my test app. And then my OutlinePicker follows. Looks quite similar, doesn’t it?

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert