iosswiftuiuikitcontextmenu

Is there multiple selections for ContextMenu in SwiftUI?


In UIKit we have this:

func collectionView(  
    _ collectionView: UICollectionView,  
    contextMenuConfigurationForItemsAt indexPaths: [IndexPath],  
    point: CGPoint  
) -> UIContextMenuConfiguration?  

https://developer.apple.com/documentation/UIKit/UICollectionViewDelegate/collectionView(_:contextMenuConfigurationForItemsAt:point:)

the difference between "contextMenuConfigurationForItemAt" and "contextMenuConfigurationForItemsAt" is (item vs items)

However I couldn't find any equivalent for "contextMenuConfigurationForItemsAt" in SwiftUI iOS.
For Mac I could find, but it's not available in iOS.
Can somebody help me?

Example photo in native photo app

enter image description here


Solution

  • If you want to show a context menu when multiple items are selected, this can be done using contextMenu(forSelectionType:menu:primaryAction:).

    Here is an example to show it working:

    struct ListItem: Identifiable, Hashable {
        let id = UUID()
        let val: Int
    }
    
    struct ContentView: View {
        @State private var items: [ListItem]
        @State private var selection = Set<UUID>()
    
        init() {
            var items = [ListItem]()
            for i in 0..<10 {
                items.append(ListItem(val: i))
            }
            self.items = items
        }
    
        var body: some View {
            NavigationStack {
                List(items, selection: $selection) { item in
                    Text("Item \(item.val)")
                }
                .contextMenu(forSelectionType: ListItem.ID.self) { items in
                    Button("Delete \(items.count) \(items.count == 1 ? "item" : "items")", role: .destructive) {}
                    Button("Cancel", role: .cancel) {}
                }
                .toolbar {
                    EditButton()
                }
            }
        }
    }
    

    Animation