Press ESC to close

How to Use UIContextMenu with Swift?

Hello friends, in this article we will talk about how to use UIContextMenu with Swift. First of all, what is UIContextMenu and why is it used? we will talk about this.

UIContextMenu is an API that will allow different actions to be taken when an object on the screen is touched or held. The example I will talk about here will be from my own application. In the My Plants application, the user may want to delete the image of his own plant. While doing this, we need to do it in a way that iOS users are familiar with. So we can do the deletion using UIContextMenu. By the way, you can download the My Plants application from here.

The My Plants detail screen contains photos of the user’s plants by date. Here we show the photos uploaded by the user in the UICollectionView. If you press and hold any of the Cells containing these photos, we want the delete option to appear. Then we perform the deletion process.

There is a function for UIContextMenu in UICollectionViewDataSource. With this function, we can give this feature to Cells. Note that this function supports iOS 16 and above. You can use the function below to create a structure like the Gif above.

    func collectionView(_ collectionView: UICollectionView,
                        contextMenuConfigurationForItemsAt indexPaths: [IndexPath],
                        point: CGPoint) -> UIContextMenuConfiguration? {
        return UIContextMenuConfiguration(identifier: nil,
                                          previewProvider: nil) { [weak self] _ in
            let deleteAction = UIAction(title: NSLocalizedString("Delete", comment: ""),
                                        image: UIImage(systemName: "trash"),
                                        attributes: .destructive) { _ in
                self?.delegate?.onDeleteButtonClicked(for: indexPaths.first?.row)
            }

            return UIMenu(title: "", children: [deleteAction])
        }
    }

You can also add different actions under UIMenu Children.

If you have questions, you can reach us by e-mail or comment. You can find more Swift-related articles here.

Leave a Reply

Your email address will not be published. Required fields are marked *