DEV Community

Cover image for How To Make a Custom Picker with Multi-Selection in SwiftUI
Kyra
Kyra

Posted on • Updated on

How To Make a Custom Picker with Multi-Selection in SwiftUI

I just wanted to start out by saying that this is an abridged version of my original published version from February 23, 2022 that you can find on my website here.


Awhile back I realized I needed a control that would allow a user to select multiple elements at once. Additionally, since I was developing a multiplatform app, I wanted it to look good on both iOS and macOS while also looking good against all the other SwiftUI controls on my forms. In the end I created a simple project, to easily share it with you, using a HStack containing Text controls and a Button that opens the selection view.

Here's how it looks on both iOS and macOS with nothing selected.

The phone simulator is to the left with the macOS sample version to the right. They both show 0 selected items with an empty list below.

When you're selecting items a checkmark appears to show the selection was set... or removed.

The phone simulator is to the left with the macOS sample version to the right. On the phone you see a list of items with some checked off while on the macOS you see the same control with a popup showing the four selected items and the count below updated.

And once it's closed again the number is updated so you know how many items are selected without needing to go back in. For this sample project I also listed the selected items below to better show how to see them.

The phone simulator is to the left with the macOS sample version to the right. They both show a count of 4 selected items with a list below showing specifically what was selected.

If you’re interested in using this custom control in your code I saved it, in its entirety, to my public SimplyKyraBlog GitHub repository and, if you want a direct link, the file CustomMultiSelectionPicker.swift can be found here. The code is also shared as a Github Gist at the bottom of my post from February 23, 2022 that also includes the backstory of this control, how I developed it, a closeup of both the iOS and macOS versions, and a slight issue I had.

Hope this helps your code and you're having a great day!

Top comments (0)