Skip to main content

How to allow row selection in a list

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to allow row selection in a list 관련

SwiftUI by Example

Back to Home

How to allow row selection in a list | SwiftUI by Example

How to allow row selection in a list

Updated for Xcode 15

SwiftUI's lists support both single and multiple selection of its items, but only when your list is in editing mode.

To support single selection, first add an optional property of the same type you're using inside your list. For example, if you were using a list of integers you would have an optional Int. Once you have that, pass it to your list using its selection parameter, then make sure your list is in editing mode.

As an example, this code shows an array of strings in a list, and stores the selected item as an optional string:

struct ContentView: View {
    @State private var selection: String?

    let names = [
        "Cyril",
        "Lana",
        "Mallory",
        "Sterling"
    ]

    var body: some View {
        NavigationStack {
            List(names, id: \.self, selection: $selection) { name in
                Text(name)
            }
            .navigationTitle("List Selection")
            .toolbar {
                EditButton()
            }
        }
    }
}

Download this as an Xcode projectopen in new window

Notice that edit button in the toolbar – remember, your list must be in editing mode to support selection.

If you want multiple selection, all you need to do is change your selection property into a Set of the same type as your list array. So, if we wanted multiple selection in the previous example we'd use this:

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

Tips

Both the single and multiple selection options can be changed by you programmatically, allowing you to change which rows were selected by modifying the state yourself.

Similar solutions…
How to adjust List row separator insets | SwiftUI by Example

How to adjust List row separator insets
How to add custom swipe action buttons to a List row | SwiftUI by Example

How to add custom swipe action buttons to a List row
How to push a new view when a list row is tapped | SwiftUI by Example

How to push a new view when a list row is tapped
How to scroll to a specific row in a list | SwiftUI by Example

How to scroll to a specific row in a list
How to adjust List row separator visibility and color | SwiftUI by Example

How to adjust List row separator visibility and color

이찬희 (MarkiiimarK)
Never Stop Learning.