admin管理员组

文章数量:1353311

I am implementing drag-and-drop functionality in a UICollectionView with a 2x2 grid of buttons. My goal is to remove the cell's shadow and background color when dragging. However, after dropping the item, the cell briefly resets and then shows the shadow and background color again.

1.What I Have Tried:
Setting backgroundColor = .clear and shadowOpacity = 0 in dragPreviewParametersForItemAt:

 func collectionView(_ collectionView: UICollectionView, dragPreviewParametersForItemAt indexPath: IndexPath) -> UIDragPreviewParameters? {
    let previewParameters = UIDragPreviewParameters()
    previewParameters.backgroundColor = .clear
    previewParameters.shadowPath = UIBezierPath(rect: CGRect.zero)
    return previewParameters
}

2.Ensuring the cell resets after dropping:

func collectionView(_ collectionView: UICollectionView, performDropWith coordinator: UICollectionViewDropCoordinator) {
    guard let destinationIndexPath = coordinator.destinationIndexPath else { return }

    if let item = coordinator.items.first, let sourceIndexPath = item.sourceIndexPath {
        performBatchUpdates {
            if let movedItem = viewModels?.remove(at: sourceIndexPath.item) {
                viewModels?.insert(movedItem, at: destinationIndexPath.item)
                moveItem(at: sourceIndexPath, to: destinationIndexPath)
            }
        }
        coordinator.drop(item.dragItem, toItemAt: destinationIndexPath)

        // Force reset after drop
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            if let cell = collectionView.cellForItem(at: destinationIndexPath) {
                cell.backgroundColor = .clear
                cell.layer.shadowOpacity = 0
            }
            collectionView.reloadItems(at: [destinationIndexPath])
        }
    }
}

3.Resetting the cell inside willDisplay:

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
cell.backgroundColor = .clear
cell.layer.shadowOpacity = 0
}

Even after implementing all of these fixes, the shadow and background color reappear after dropping the item. It seems like UICollectionView is applying the default styling back to the cell after the drag-and-drop operation completes.

Question: Why does the shadow and background color return after dropping the item? How can I ensure that the cell remains with backgroundColor = .clear and shadowOpacity = 0 after being dropped? Is there something I’m missing about UICollectionViewCell reuse or state restoration that’s causing this issue?

Any help is greatly appreciated!

本文标签: swiftUICollectionViewCell Shows Shadow and Background After Drop (Drag amp Drop Issue)Stack Overflow