UICollectionView support for drag/drop reordering AND context menus

Viewed 366

I'm trying to implement reordering AND context menus in a UICollectionView using the instance methods moveItemAt and contextMenuConfigurationForItemAt. Both solutions work fine on their own but when I try to implement both of them in the UICollectionView the contextual menus take precedence and I'm not able to use drag and drop reordering.

Is there a way to use both of these methods in the same collection view? Alternatively, is anyone familiar with a way to support these features using another solution? I'm currently looking into implementing Drag/Drop delegate as a workaround.

Below is an example of the code I'm using. This project is targeting iOS14.

extension myViewController {
    override func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        let temp = items.remove(at: sourceIndexPath.item)
        items.insert(temp, at: destinationIndexPath.item)
    }

    override func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
        let index = indexPath.row
        
        let config = UIContextMenuConfiguration(
            identifier: nil,
            previewProvider: nil){ [self] _ in
            return UIMenu(
                title: "",
                image: nil,
                identifier: nil,
                children: [deleteAction(index: index),editAction(index: index)])
        }
        return config
    }
}
1 Answers

Replace your use of the moveItemAt API with the new drag and drop APIs, and you'll get this behaviour for free!

Related