SwiftUI - list with multi-select (not a custom one)
Asked Answered
T

1

8

How to make a list with multi-select in SwiftUI? I know I can make a custom one like this: https://mcmap.net/q/392669/-select-multiple-items-in-swiftui-list

But is there a default one already in SwiftUI?

Here is an example of multi-select controls in Apple's Mail app:

Apple Mail app

The same controls are also used in Apple Photos when you select multiple photos. These controls are also in Apple's official iOS Sketch Library which you can download from here: https://developer.apple.com/design/resources/

There are very similar controls in Apple's Reminders App:

Apple Reminders app

Throne answered 14/5, 2021 at 4:0 Comment(0)
E
14

Yes, SwiftUI's list has this capability built in. You need to provide a Set for the selection parameter of the list for multiple selections. I'm also setting the edit mode to .active by default, which is optional.

struct ContentView: View {
    @State private var selection = Set<String>()
    @State private var isEditMode: EditMode = .active
    
    let items = [
        "Item 1",
        "Item 2",
        "Item 3",
        "Item 4"
    ]

    var body: some View {
        NavigationView {
            List(items, id: \.self, selection: $selection) { name in
                Text(name)
            }
            .toolbar {
                EditButton()
            }
            .environment(\.editMode, self.$isEditMode)
        }
    }
}

Euboea answered 14/5, 2021 at 4:14 Comment(3)
Awesome! I didn't know about @State private var isEditMode: EditMode = .active. 2 questions: 1. Can you use your solution in forms? So for example, user will create new item and will see few options to (multi)select. And later I could save info about what was selected per this item? 2. Can you change background color of selected items from default grey one?Throne
1) In my limited experiment of trying to embed it in a Form, it did not seem to work. 2) Not that I know of. Perhaps there's some sort of combination of list styles and modifiers, but nothing works in an obvious way.Euboea
Thanks. I will experiment how to use it in Forms.Throne

© 2022 - 2024 — McMap. All rights reserved.