onmyway133 / blog

šŸ What you don't know is what you haven't learned
https://onmyway133.com/
MIT License
669 stars 33 forks source link

How to select in List in SwiftUI #881

Open onmyway133 opened 2 years ago

onmyway133 commented 2 years ago

Specify optional value for List(selection:).

This keeps selection on macOS, but not on iPad. On iPad each row in the List needs to be NavigationLink, no need for .tag. The selection is not updated, need to manually update with onTapGesture

For List selection to work, make sure

struct Sidebaer: View {
    class ViewModel: ObservableObject {
        @Published var group: BookGroup?
    }

    @StateObject private var vm = ViewModel()

    var body: some View {
        List(selection: $vm.group) {
            allView
            foldersView
            tagsView
        }

Note that

List(selection: $selectedItem) {
    ForEach(manager.stack.items) { item in
        ItemCell(item: item)
            .onDrag {
                NSItemProvider(object: item.text as NSString)
            }
            .tag(item)
    }
    .onMove { source, destination in
        manager.stack.items.move(fromOffsets: source, toOffset: destination)
    }
    .onDelete { indexSet in
        manager.stack.items.remove(atOffsets: indexSet)
    }
    .onInsert(of: [.text, .url]) { index, itemProviders in
        manager.handleInsert(at: index, itemProviders: itemProviders)
    }
}