GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

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!

Go further, faster with the Swift Career Accelerator.

GO FURTHER, FASTER Unleash your full potential as a Swift developer with the all-new Swift Career Accelerator: the most comprehensive, career-transforming learning resource ever created for iOS development. Whether you’re just starting out, looking to land your first job, or aiming to become a lead developer, this program offers everything you need to level up – from mastering Swift’s latest features to conquering interview questions and building robust portfolios.

Learn more here

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.