Lawrence Gimenez
Lawrence Gimenez

Reputation: 3235

Change the background color of a Context Menu using Swift

I am implementing UIContextMenu on a UICollectionViewCell. Inside the UICollectionViewCell there is a button with a radius of 15. When I tap on a UICollectionViewCell this is the result enter image description here. What I want is just the button without the white background. I already tried UICollectionViewCell.backgroundColor = .clear and seems not working. If anyone can help me thanks!

Upvotes: 2

Views: 4415

Answers (3)

Borut Tomazin
Borut Tomazin

Reputation: 8138

You have UIPreviewParameters where you can change backgroundColor easily.

Upvotes: 1

Mikial
Mikial

Reputation: 31

Add let identifier = "\(indexPath.row)" as NSString in your collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? function.

Put that identifier in the UIContextMenuConfiguration(identifier: identifier, previewProvider: previewProvider, actionProvider: actionProvider) init.

Next add this func

func collectionView(_ collectionView: UICollectionView, previewForHighlightingContextMenuWithConfiguration configuration: UIContextMenuConfiguration) -> UITargetedPreview? {
        guard
            let identifier = configuration.identifier as? String,
            let index = Int(identifier),
            let cell = collectionView.cellForItem(at: IndexPath(row: index, section: 0)) as? YourCell

              else {
                return nil
            }
        return UITargetedPreview(view: cell.YourButton)
    } 

Upvotes: 3

King.lbt
King.lbt

Reputation: 881

I think in your UICollectionViewCell, call contentView.backgroundColor = .clear will work.

enter image description here

Can you provide further info ? Because my code works.

Upvotes: -3

Related Questions