TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Letting users select items in a List

Paul Hudson    @twostraws   

It's common to place a NavigationLink inside a List row so that users can tap on a row and see more information, but sometimes you want more control – you want tapping to merely select an item, so you can take some kind of action later.

First, here's a simple List that has no selection, and just shows several strings:

struct ContentView: View {
    let users = ["Tohru", "Yuki", "Kyo", "Momiji"]

    var body: some View {
        List(users, id: \.self) { user in
            Text(user)
        }
    }
}

Making that work with selection takes three steps, starting with creating some state to store whatever row is tapped. As our list shows strings, this means making the selected value be an optional string – nothing will be selected by default, but it will contain a user's name when their row is tapped on.

So, we'd need to add this property to the view:

@State private var selection: String?

Next, we need to tell our list to update that state when a row is tapped. This is a two-way binding, which means tapping a row updates the property, but also updating the property will select the row.

Here's how that looks:

List(users, id: \.self, selection: $selection) { user in
    Text(user)
}

And third, we can now go ahead and use that selection somehow. For example, we could show some text below the list if there's a selection:

if let selection {
    Text("You selected \(selection)")
}

If you want to upgrade this to handle multiple selection, you need to change the selection property so that it stores a set of values. This can be empty by default, to mean nothing is selected:

@State private var selection = Set<String>()

And when it comes to displaying the selection, we can call formatted() on the set to display all the names as a single string:

if selection.isEmpty == false {
    Text("You selected \(selection.formatted())")
}

Of course, the real challenge here is how you enable multiple selections, because tapping on one row will automatically unselect the previous row.

iOS does have a fairly hidden gesture for activating multi-select mode: if you swipe horizontally on your data using two fingers, it will activate. If you're using the simulator, you need to hold down the Option key to enable two-finger mode, then also hold down the Shift key to enable swiping, and now swipe from left to right on the list.

Although both of those work, neither are terribly obvious. A better idea is to add an EditButton, which automatically handles enabling or disabling editing and therefore also enables or disables multi-select mode. So, put this somewhere in your layout:

EditButton()

Now you should be able to enter and exit multi-select mode freely, then tap checkboxes next to each list row to add it to your selection. What you then do with your selection is up to you!

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 5.0/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.